我以爲我知道JavaScript,似乎我不知道。使用`this`與對象文字
我想定義一個像這樣的對象。 (從http://www.phpied.com/3-ways-to-define-a-javascript-class/例)
var apple = {
type: "macintosh",
color: "red",
getInfo: function() {
return this.color + ' ' + this.type + ' apple';
}
}
嗯,這看起來不錯,讓我們打印信息...
apple.getInfo() //returns "red macintosh apple" as expected
OK,現在就功能並再次運行...
var func = apple.getInfo; func(); //returns "undefined undefined apple"
那麼,那不是我所期望的。顯然,this
被解釋爲window
。這不是我想要的。
我的問題是 - 什麼是重寫apple
文字的慣用,首選方法,以便apple.getInfo
返回一個函數,可以單獨運行,但仍然使用對象屬性?
另請參閱http://stackoverflow.com/questions/20279484/how-to-access-the-correct-this-context-inside-a-callback –