// Situation 1
var a = function A() {
this.x = 1;
var b = function B () {
this.x = 2;
console.log('Method B : x = ' + this.x);
};
console.log('Method A : x = ' + this.x);
b();
}
当我调用 a() 时,我的结果是
Method A : x = 1
Method B : x = 2
但是如果我删除“this.x = 2”:
// Situation 2
var a = function A() {
this.x = 1;
var b = function B () {
console.log('Method B : x = ' + this.x);
};
console.log('Method A : x = ' + this.x);
b();
}
我的结果是
Method A : x = 1
Method B : x = 1
不明白为什么
- 情况 2:函数 B 的“this”引用函数 A 的“this”
但是
- 情况 1:在函数 B 中赋值“this.x = 2”时,函数 A 的“this.x”没有改变
我的代码在 Chrome v23 上运行
最佳答案
由于 this.x = 2
位于函数 B 的定义中,因此只有在调用 B 时(而不是定义它时),它才会发生。尝试这个版本并查看:
// Situation 3
var a = function A() {
this.x = 1;
var b = function B () {
this.x = 2;
console.log('Method B : x = ' + this.x);
};
console.log('Method A before B: x = ' + this.x);
b();
console.log('Method A after B: x = ' + this.x);
}
关于javascript - 函数调用 javascript 中的 "this",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13999660/