为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

Smart猫小萌 2019-12-26 11:14:14
我有一个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?
查看完整描述

3 回答

?
慕斯709654

TA贡献1840条经验 获得超5个赞

this始终是调用方法的对象。但是,将方法传递给时then(),您不会调用它!该方法将存储在某个位置,稍后再从那里调用。如果要保存this,则必须这样做:


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

或者,如果您必须在ES6之前的版本中执行此操作,则需要保留以下内容this:


var that = this;

// ...

.then(function() { that.method2() })


查看完整回答
反对 回复 2019-12-26
?
神不在的星期二

TA贡献1963条经验 获得超6个赞

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是实例的原因。


查看完整回答
反对 回复 2019-12-26
?
幕布斯7119047

TA贡献1794条经验 获得超8个赞

基本上,您要向其传递没有上下文引用的函数引用。可以通过this几种方式确定上下文:

  1. 隐含地。调用全局函数或没有绑定的函数会假定全局上下文。*

  2. 直接参考。如果您致电,myObj.f()myObj将是this上下文。**

  3. 手动装订。这是您的函数类,例如.bind.apply。这些您明确声明了this上下文。这些总是优先于前两个。

在您的示例中,您正在传递一个函数引用,因此在调用它时,它暗示是全局函数或没有上下文的函数。使用.bind通过在this显式设置的位置创建新函数来解决此问题。

*仅在非严格模式下如此。在严格模式下,this设置为undefined

**假设您使用的功能尚未手动绑定。


查看完整回答
反对 回复 2019-12-26
  • 3 回答
  • 0 关注
  • 621 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信