2016-11-06 80 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