【发布时间】:2012-01-11 03:43:50
【问题描述】:
我有 2 个代码块,一个不工作,另一个工作,因为我指定了 = this 并在我的函数中使用 that 而不是 this。有人可以帮我理解为什么会这样。如果我说得对(如果不是,请赐教),这将有助于了解人们应该如何考虑访问 JavaScript 中对象的函数中的变量,以及“this”的性质。谢谢!
var add = function (x, y) {
return x + y;
}
var myObject = {
value: 0,
increment: function (inc) {
this.value += typeof inc === 'number' ? inc : 1;
}
};
myObject.double2 = function () {
// var that = this;
var helper = function () {
this.value = add(this.value, this.value)
};
helper();
};
myObject.increment(100);
document.writeln(myObject.value); // Prints 100
myObject.double2();
document.writeln('<BR/>'); // Prints <BR/>
document.writeln(myObject.value); // Prints 100, **FAILS**
以及修改后的代码:
var add = function (x, y) {
return x + y;
}
var myObject = {
value: 0,
increment: function (inc) {
this.value += typeof inc === 'number' ? inc : 1;
}
};
myObject.double2 = function () {
var that = this;
var helper = function () {
that.value = add(that.value, that.value)
};
helper();
};
myObject.increment(100);
document.writeln(myObject.value); // Prints 100
myObject.double2();
document.writeln('<BR/>'); // Prints <BR/>
document.writeln(myObject.value); // Prints 200 - **NOW IT WORKS**
【问题讨论】:
-
this指的是本地执行上下文。 (我 100% 肯定其他人可以说得比我好。)您的that变量是一个闭包,它捕获this的值,以便您可以在函数调用内部引用它,无论何时发生,在未来的某个时候。
标签: javascript