我有一个javascript类,每个方法都返回Q个promise .我想知道为什么thismethod2method3中没有定义.有没有更正确的方法来编写这段代码?

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吗?

推荐答案

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

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

或者,如果必须按照ES6之前的方式进行,则需要在以下情况之前保存this个:

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

Node.js相关问答推荐

AWS Lambda呼叫未登录控制台

序列化事务未按预期工作

JEST模拟由http服务器控制器导入的ES模块

获取页面大小为10的所有文章,每篇文章填充一些所需的用户信息

向url传递多个参数

TS 后端开发:prismagenerate找不到已安装的@tsed/prisma包

有没有办法判断 UUID 是否是使用 node.js 中的特定命名空间生成的?

在 getServerSideProps 中使用 EmailProvider 获取 NextAuth 会话会抛出 fs找不到模块

为什么我不能将 id 发送到后端并通过 findByIdAndRemove() 删除项目?

Axios GET 返回不可读的响应

使用中的端口代码:'EADDRINUSE',即使在 kill 命令之后

node.js 中 res.setHeader 和 res.header 的区别

如何使用适用于 Node.js 的 AWS 开发工具包将 Amazon S3 中的所有对象从一个前缀复制/移动到另一个前缀

如何在 Node.js 中等待子进程完成

使用 pg-promise 进行多行插入

Puppeteer:如何提交表单?

node.js 模块和函数中this的含义

Meteor - collection.find() 总是返回所有字段

如何判断MongoDB本机nodejs驱动程序中是否存在集合?

npm install - javascript堆内存不足