为什么在使用诺言时在类方法中未定义“ this”?

我有一个javascript类,每个方法都返回一个QPromise。我想知道为什么this在method2和中未定义method3。有没有更正确的方法来编写此代码?


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;

};

我可以使用解决此问题bind:


function MyClass(opts){

  this.options = opts;


  return this.method1()

    .then(this.method2.bind(this))

    .then(this.method3.bind(this));

}

但是不能完全确定为什么bind有必要。正在.then()消灭this?


Smart猫小萌
浏览 626回答 3
3回答

慕斯709654

this始终是调用方法的对象。但是,将方法传递给时then(),您不会调用它!该方法将存储在某个位置,稍后再从那里调用。如果要保存this,则必须这样做:.then(() => this.method2())或者,如果您必须在ES6之前的版本中执行此操作,则需要保留以下内容this:var that = this;// ....then(function() { that.method2() })

神不在的星期二

window默认情况下,在全局对象()的上下文中调用Promise处理程序。在严格模式(use strict;)中,上下文为undefined。这就是method2和发生的事情method3。;(function(){  'use strict'  Promise.resolve('foo').then(function(){console.log(this)}); // undefined}());;(function(){  Promise.resolve('foo').then(function(){console.log(this)}); // window}());因为method1,您打电话method1为this.method1()。这种调用方式在this您的实例对象的上下文中调用它。这就是为什么内部上下文method1是实例的原因。

幕布斯7119047

基本上,您要向其传递没有上下文引用的函数引用。可以通过this几种方式确定上下文:隐含地。调用全局函数或没有绑定的函数会假定全局上下文。*直接参考。如果您致电,myObj.f()那myObj将是this上下文。**手动装订。这是您的函数类,例如.bind和.apply。这些您明确声明了this上下文。这些总是优先于前两个。在您的示例中,您正在传递一个函数引用,因此在调用它时,它暗示是全局函数或没有上下文的函数。使用.bind通过在this显式设置的位置创建新函数来解决此问题。*仅在非严格模式下如此。在严格模式下,this设置为undefined。**假设您使用的功能尚未手动绑定。
打开App,查看更多内容
随时随地看视频慕课网APP