2016-11-06 129 views
-2

我知道這是完全無意義的代碼我只是用我已經寫好的代碼進行匿名函數試驗。我不明白爲什麼它沒有返回數組?爲什麼不是這個匿名函數返回?

(function() { 
    function Employee(name, age, pay) { 
     this.name = name; 
     this.age = age; 
     this.pay = pay || 800; 
    } 

    function Manager(name, age, pay) { 
     Employee.call(this, name, age, pay); 
     this.reports = []; 
    } 
    Manager.prototype = Object.create(Employee.prototype); 
    Manager.prototype.addReport = function(report) { 
     this.reports.push(report); 
    } 

    function Cashier(name, age, pay) { 
     Employee.call(this, name, age, pay); 
    } 
    Cashier.prototype = Object.create(Employee.prototype); 
    var ary = [Cashier, Manager]; 
    return ary; 
}()); 
+1

尋求幫助時,抽出時間來始終如一格式化代碼和可讀性很強將有助於你得到的答案。 *(我這次爲你做了。)* –

+2

數組_is_返回。 – thgaskell

+0

完全同意@ T.J.Crowder。現在,_Anonymous_函數不能被調用,對吧?那麼,你究竟在哪裏檢查他們是否返回一些東西。另外,我想知道使用匿名函數的必要性。對我而言,如果有一種定義函數的標準方式,代碼審查就容易得多。等價物將定義一個命名的函數並在它被定義之後調用它。它不是更清楚嗎? – FDavidov

回答

1

...爲什麼陣列沒有返回?

它是。你只是沒有做任何回報價值的事情;看到第一行***評論:

var result = (function() { // **** 
 
    function Employee(name, age, pay) { 
 
     this.name = name; 
 
     this.age = age; 
 
     this.pay = pay || 800; 
 
    } 
 

 
    function Manager(name, age, pay) { 
 
     Employee.call(this, name, age, pay); 
 
     this.reports = []; 
 
    } 
 
    Manager.prototype = Object.create(Employee.prototype); 
 
    Manager.prototype.addReport = function(report) { 
 
     this.reports.push(report); 
 
    } 
 

 
    function Cashier(name, age, pay) { 
 
     Employee.call(this, name, age, pay); 
 
    } 
 
    Cashier.prototype = Object.create(Employee.prototype); 
 
    var ary = [Cashier, Manager]; 
 
    return ary; 
 
}()); 
 
console.log(result);

+0

好吧,我的印象是,你從函數中返回一個對象,它可以從它返回的範圍中訪問,所以我想我通過鍵入'ary'從全局訪問控制檯中的ary對象。那麼我認爲我錯了? – Brandon

+0

@Brandon:是的,'ary'(變量)只能通過匿名函數中的代碼訪問。這就是上面匿名函數的*目的:除了那些你選擇通過返回來訪問它們的東西外,將它們保持爲私有。它引用的數組是可訪問的,但只有在使用匿名函數返回的值時纔是可訪問的。 –

1

其實,此代碼返回兩個構造函數對象。試試你的控制檯上運行它: -

enter image description here

+1

除了添加快照之外,您可以將OP代碼複製到堆棧片段中。 – Rajesh

+0

對不起,我看到了我應該說的那個對象,那就是我困惑的原因之一。當我在控制檯輸入obj時,它說obj是'未定義的'? – Brandon