下面的代码在常规函数的情况下可以工作,但在对象方法的情况下不起作用。
我收到以下错误:
return this.anotherService.get1(start, end);
^
TypeError: Cannot read property 'anotherService' of undefined
如何重写代码以使 getTransactions
成为执行作为参数传递的不同方法的通用辅助函数?
class Service {
constructor(arg1) {
this.anotherService= new AnotherService(arg1);
}
getMethod1(start, end) {
return this.anotherService.get1(start, end);
}
getMethod2(start, end) {
return this.anotherService.get2(start, end);
}
}
function getTransaction1(arg1, arg2, arg3) {
let service = new Service(arg1);
getTransactions(arg2, arg3, service.getMethod1);
};
function getTransaction2(arg1, arg2, arg3) {
let service = new Service(arg1);
getTransactions(arg2, arg3, service.getMethod2);
};
function getTransactions(arg2, arg3, func) {
let start = ......;
let end = ........;
func(start, end).then(data => {
res.json(data);
}).catch(console.log);
};
最佳答案
您可以使用Function#bind
来处理:
function getTransaction1(arg1, arg2, arg3) {
let service = new Service(arg1);
getTransactions(arg2, arg3, service.getMethod1.bind(service));
// -------------------------------------------^^^^^^^^^^^^^^
}
function getTransaction2(arg1, arg2, arg3) {
let service = new Service(arg1);
getTransactions(arg2, arg3, service.getMethod2.bind(service));
// -------------------------------------------^^^^^^^^^^^^^^
}
Function#bind
返回一个新函数,该函数在调用时将调用原始函数,并将 this
设置为您传递给 bind
的对象。 (您还可以向 bind
传递其他参数,但这与此处无关。)
或者,当然,您可以使用粗箭头函数在构造函数中创建 getMethod1
和 getMethod2
,这会获取词法 this
绑定(bind):
class Service {
constructor(arg1) {
this.anotherService= new AnotherService(arg1);
this.getMethod1 = (start, end) => {
return this.anotherService.get1(start, end);
};
this.getMethod2 = (start, end) => {
return this.anotherService.get2(start, end);
};
}
}
...在这种情况下,您根本不必更改 getTransaction1
和 getTransaction2
。
旁注:函数声明(您与getTransaction1
和getTransaction2
一起使用的)不是语句,因此它们不是' t 以分号终止。
关于javascript - 将构造对象的方法传递给 JavaScript 中的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30014469/