已知如下代碼:var foo = 1;var bar = 10;function a (arg, func) { this.foo = arg + this.bar;
func(this.foo);
}var b = { foo: 100, bar: 1000};
a.call(b, 10000, function(x) { console.log(this.foo + x);
});問: 該代碼執行后控制臺打印結果是什么?分析產生該結果的原因。我本來以為執行結果會是22000,因為直接把call中的參數帶入函數a后是:function a (arg, func) { this.foo = arg + this.bar; console.log(this.foo + this.foo);
}然后由于arg = 10000,b.foo = arg + b.bar = 10000 + 1000 = 11000,11000 + 11000 = 22000.但是執行結果卻是11001,也就是說console.log里的this指向的是window,對此我表示不解,既然這個function是作為a的參數帶入的,既然a的this被指向了b,為什么這里的this不會指向b呢?希望各位高手解惑。另外,如果這個this不指向b,有沒有什么方法在仍使用this.foo的情況下將這個this指向b?
javascript Function.call中的this指向問題
MYYA
2018-09-11 13:25:36