我想知道並理解這個和那個之間的不同,以及何時需要使用它。 我準備好了嗎許多後,很多教程,但我不明白,但這和那個有什麼區別
這是我的課
function Container(param) {
function dec() {
if (secret > 0) {
secret -= 1;
return true;
} else {
return false;
}
}
this.member = param;
var secret = 3;
var that = this;
this.service = function() {
console.log(this.member); // foo
console.log(that.member); // foo
return dec() ? that.member : null;
};
}
新
var myContainer = new Container('foo');
myContainer.service()
調用myContainer.service()
將返回「ABC」的第一個三次它叫做。 之後,它將返回null
爲什麼我必須要做var that = this
??
另請參閱http://stackoverflow.com/questions/3127429/javascript-this-keyword – elclanrs
您是否嘗試過不使用''來查看會發生什麼?可能是瞭解發生了什麼的好方法。 – CoderDennis
在你的例子中,我沒有看到「that」的需要。試試'var s = myContainer.service; s()'看看有沒有'that'發生了什麼。 – phylax