gpt4 book ai didi

javascript - ES6 类方法在内部引用类实例的最有效方式

转载 作者:行者123 更新时间:2023-11-30 08:33:48 26 4
gpt4 key购买 nike

给定下面的类,我如何在返回 promise 的方法中引用类的实例?

我是否必须在每个返回 promise 的方法中执行 var self = this

class Group {

constructor() {}

foo() {

// 'this' references the class instance here
console.log(this.myProp); => 'my value'

// could do this 'var self = this' but do i need to add this code to every method that returns a promise?

return Q.promise(function(resolve, reject) {
// 'this' does NOT reference the class instance here
});
}
}

最佳答案

如果您不需要 promise 的上下文,请使用箭头函数

class Group {

constructor() {}

foo() {

// 'this' references the class instance here
console.log(this.myProp); => 'my value'

// could do this 'var self = this' but do i need to add this code to every method that returns a promise?

return Q.promise((resolve, reject) => {
// 'this' references the class instance here
});
}
}

关于javascript - ES6 类方法在内部引用类实例的最有效方式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34158802/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com