下面是在JavaScript中兩個被廣泛看作代碼片段:這些是什麼意思?
Function.prototype.method = function (name, func) {
this.prototype[name] = func;
return this;
};
Number.method('integer', function() {
return Math[this < 0 ? 'ceil' : 'floor'](this);
});
很明顯,在第二個片段的this
代表的是調用了增強integer
方法Number對象。第一個片段中的this
怎麼樣?從prototype
屬性我們可以猜到它代表了正在增強的構造函數,但片段背後的邏輯對我來說是難以捉摸的。任何人都可以詳細解釋?謝謝。
'this'可以表示任何東西,尤其是當函數被underscore.js的'bind'和'bindAll'祕密綁定時,所以答案從來就不是這樣。然而,[這裏](http://www.quirksmode.org/js/this.html)是一個高級參考。 – Brian
請參閱我對這個其他問題的回答,以瞭解「this」在javascript中的行爲。這不像大多數其他語言:http://stackoverflow.com/questions/13441307/how-does-the-this-keyword-in-javascript-act-within-an-object-literal/13441628#13441628 – slebetman