使用promises时,为什么'this'在类方法中未定义? [英] Why is 'this' undefined inside class method when using promises?

查看:143
本文介绍了使用promises时,为什么'this'在类方法中未定义?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个javascript类,每个方法返回一个 Q 的承诺。我想知道为什么这个 method2 method3 。是否有更正确的方法来编写此代码?

  function MyClass(opts){
this.options = opts ;

返回this.method1()
.then(this.method2)
.then(this.method3);
}

MyClass.prototype.method1 = function(){
// ... q stuff ...

console.log(this可供选项); //记录opts对象

return deferred.promise;
};

MyClass.prototype.method2 = function(method1resolve){
// ... q stuff ...

console.log(this); // logs undefined

return deferred.promise;
};

MyClass.prototype.method3 = function(method2resolve){
// ... q stuff ...

console.log(this); // logs undefined

return deferred.promise;
};

我可以通过 bind 解决这个问题:

  function MyClass(opts){
this.options = opts;

返回this.method1()
.then(this.method2.bind(this))
.then(this.method3.bind(this));
}

但不完全确定为什么 bind 是必要的;是 .then()查杀关闭?

解决方案

始终是调用该方法的对象。但是,当将方法传递给然后()时,你没有调用它!该方法将存储在某处并在稍后从那里调用。如果你想保留这个,你必须这样做:

  .then(()=> this.method2())

或者如果你有要按照ES6之前的方式进行,您需要在<$ p

$ $ $ $ code> var that = this;
// ...
.then(function(){that.method2()})


I have a javascript class, and each method returns a Q promise. I want to know why this is undefined in method2 and method3. Is there a more correct way to write this code?

function MyClass(opts){
  this.options = opts;

  return this.method1()
    .then(this.method2)
    .then(this.method3);
}

MyClass.prototype.method1 = function(){
  // ...q stuff...

  console.log(this.options); // logs "opts" object

  return deferred.promise;
};

MyClass.prototype.method2 = function(method1resolve){
  // ...q stuff...

  console.log(this); // logs undefined

  return deferred.promise;
};

MyClass.prototype.method3 = function(method2resolve){
  // ...q stuff...

  console.log(this); // logs undefined

  return deferred.promise;
};

I can fix this by using bind:

function MyClass(opts){
  this.options = opts;

  return this.method1()
    .then(this.method2.bind(this))
    .then(this.method3.bind(this));
}

But not entirely sure why bind is necessary; is .then() killing this off?

解决方案

this is always the object the method is called on. However, when passing the method to then(), you are not calling it! The method will be stored somewhere and called from there later. If you want to preserve this, you will have to do it like this:

.then(() => this.method2())

or if you have to do it the pre-ES6 way, you need to preserve this before:

var that = this;
// ...
.then(function() { that.method2() })

这篇关于使用promises时,为什么'this'在类方法中未定义?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆