已知如下代码:
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
?