2014-11-05 55 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