已知如下代码:
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?
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号
因为你在传func的时候没指定this,传了一个匿名函数,然后在
a里面直接执行了没指定this,在非严格模式下,this指向window。因为call强制绑定了this,所以执行时a中的this确实是b,执行a中的func时,这可是一个匿名函数,肯定是绑定在window上了
就可以将该匿名函数的
this绑定到b上。call第一个参数即是调用方法的执行者,它可以改变this所指代的对象。