【发布时间】:2018-12-23 14:00:11
【问题描述】:
我正在使用 node v8.9.4 测试我的代码
我想在我的 Promise 链中使用类方法。但这失败并出现错误:
(node:68487) UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 1): TypeError: Cannot read property 'attr' of undefined
const fsp = require('fs-promise');
class MyClass {
constructor() {
this.attr = 'value';
}
promiseMe() {
console.log(this.attr);
}
main() {
fsp.readdir('.').then(this.promiseMe);
}
}
new MyClass().main();
所以我尝试使用箭头函数作为类方法。
但是将箭头函数定义为类方法在语法上是不正确的:
Unexpected token =
promiseMe = () => {
console.log(this.attr);
}
这行得通,但它真的很难看:
const fsp = require('fs-promise');
class MyClass {
constructor() {
this.attr = 'value';
this.promiseMe = () => {console.log(this.attr);}
}
main() {
this.promiseMe();
}
}
new MyClass().main();
那么如何在 Promise 中使用类方法呢?
关于这个话题还有一个问题: How to use arrow functions (public class fields) as class methods? 不幸的是,这不适用于我的 node.js 设置。
【问题讨论】:
-
箭头函数作为方法在被调用时不会正确设置
this。 -
“我想在我的 Promise 链中使用类方法。” ->
somePromise.then(someClass.someMethod.bind(someClass))用于“类方法”或somePromise.then(someInstance.someMethod.bind(someInstance))用于“实例方法” -
注意你也可以使用
fsp.readdir('.').then(x => this.promiseMe(x))
标签: javascript ecmascript-6 arrow-functions