javascript Function.call中的this指向问题

已知如下代码:

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的参数带入的,既然athis被指向了b,为什么这里的this不会指向b呢?希望各位高手解惑。另外,如果这个this不指向b,有没有什么方法在仍使用this.foo的情况下将这个this指向b

阅读 3.7k
5 个回答
function a (arg, func) {
  this.foo = arg + this.bar;
  (func.bind(this))(this.foo);
}

因为你在传func的时候没指定this,传了一个匿名函数,然后在a里面直接执行了没指定this,在非严格模式下,this指向window。

因为call强制绑定了this,所以执行时a中的this确实是b,执行a中的func时,这可是一个匿名函数,肯定是绑定在window上了

a.call(b, 10000, function(x) {
  console.log(this.foo + x);
}.bind(b));

就可以将该匿名函数的 this 绑定到 b 上。

call第一个参数即是调用方法的执行者,它可以改变this所指代的对象。

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题