我有一个函数需要传递给我在nodeJs中定义的类。 用例场景是我想让类的实现者控制如何处理从createCall函数接收的数据。我不介意该方法是否成为该类的成员函数。任何帮助将不胜感激。
//Function to pass. Defined by the person using the class in their project.
var someFunction = function(data){
console.log(data)
}
//And I have a class i.e. the library.
class A {
constructor(user, handler) {
this.user = user;
this.notificationHandler = handler;
}
createCall(){
var result = new Promise (function(resolve,reject) {
resolve(callApi());
});
//doesn't work. Keeps saying notificationHandler is not a function
result.then(function(resp) {
this.notificationHandler(resp);
}) ;
//I want to pass this resp back to the function I had passed in the
// constructor.
//How do I achieve this.
}
callApi(){ ...somecode... }
}
// The user creates an object of the class like this
var obj = new A("abc@gmail.com", someFunction);
obj.createCall(); // This call should execute the logic inside someFunction after the resp is received.
答案 0 :(得分:1)
箭头功能(如果你的节点版本支持它们)在这里很方便:
class A {
constructor(user, handler) {
this.user = user;
this.notificationHandler = handler;
}
createCall() {
var result = new Promise(resolve => {
// we're fine here, `this` is the current A instance
resolve(this.callApi());
});
result.then(resp => {
this.notificationHandler(resp);
});
}
callApi() {
// Some code here...
}
}
在箭头内部函数中,this
指的是定义此类函数的上下文,在我们的示例中是A
的当前实例。旧学校方式(ECMA 5)将是:
createCall() {
// save current instance in a variable for further use
// inside callback functions
var self = this;
var result = new Promise(function(resolve) {
// here `this` is completely irrelevant;
// we need to use `self`
resolve(self.callApi());
});
result.then(function(resp) {
self.notificationHandler(resp);
});
}