2014-11-05 44 views
2

当尝试使用私有静态方法的方法时,我遇到了这种非常奇怪的行为。在下面的代码中,公共方法getData被它自己的返回数据覆盖,尽管它从未被明确调用!这对我来说很奇怪,并想知道这里发生了什么。我认为它不仅适用于根据模块模式包含匿名函数中的整个页面,而且还希望了解这个错误。在匿名函数中扩展原型 - 奇怪的效果

function MyClass() { 
    this._prop = true; 
} 
MyClass.prototype.getData = function() { 
    this._prop = false; 
    return { a: 2344, b: 765, c: 234 }; 
} 

(function() { 
    var privateStatic = 0; 
    MyClass.prototype.getCount = function() { 
     return privateStatic++; 
    } 
}()); 

var m = new MyClass(); 
console.log(m.getData()); //Error (object is not a function) 
console.log(m.getData); //prints {a:2344,b:765,c:234} 
+2

您需要getData方法赋值后的半(;);这是一个表达。否则该函数会传递您的匿名结果,并将其结果分配给instance.getData – dandavis 2014-11-05 20:02:00

回答

0

这样做的原因奇怪的行为是的getData被立即调用由于函数声明之后缺少一个分号(伟大的地方,dandavis)和IIFE后直它,包裹在括号。从本质上讲,这一点:

MyClass.prototype.getData = function() { 
    this._prop = false; 
    return { a: 2344, b: 765, c: 234 }; 
} // Notice no semicolon here! 
(function() { 
    var privateStatic = 0; 
    MyClass.prototype.getCount = function() { 
    return privateStatic++; 
    } 
}()); 

变为这样:

MyClass.prototype.getData = function() { 
    this._prop = false; 
    return { a: 2344, b: 765, c: 234 }; 
}(); 

所以这是的getData属性设置为函数的返回值。因此,为什么m.getData打印出{ a: 2344, b: 765, c: 234 }m.getData()不起作用(它不再是一个功能!)。

+0

Javascript中的可选分号再次触发!感谢jayrobin和dandavis解释了什么似乎是最黑暗的黑色魔术师。 – wedstrom 2014-11-05 20:50:22