我有2個街區的代碼,一個不工作,一個工作,因爲我分配一個=這和使用,在我的函數而不是這個。有人能幫助我理解爲什麼這樣。這有助於瞭解如何在JavaScript中使用對象中的函數來訪問變量,以及「this」的性質,如果我說得對(如果不是,請賜教)。謝謝!理解「這種」在Javascript
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%確定別人能說得更好,然後我)。你的'''''''''''變量是一個閉包,它捕獲'this'的值,以便在函數調用中引用它,在未來的某個時候。 – asawyer 2012-01-11 03:49:50