[英]How to bind this with Higher order functions
我在某个文件中有这个高阶函数
withTry.js
function withTry(func){
return function(...args) {
try{
func(...args);
}
catch(error){
console.log(`ERROR: ${error}`)
}
}
}
我试图在另一个文件中调用它;
foo.js
const withTry = require('path');
function someClass(){
this.m = null;
this.s=0;
}
/*I am using the withTry in class prototypes*/
someClass.prototype.func = withTry(function(data){
/*
The problem is here
The value of "this" is global which makes sense because it refers to the global of the withTry HOF
*/
console.log(this.s) /*undefined*/
});
我的问题是如何绑定“someClass”的“this”
你不想绑定它,你想通过动态传递this
值:
function withTry(func) {
return function(...args) {
try {
func.call(this, ...args);
// ^^^^^^^^^^^
} catch(error){
console.log(`ERROR: ${error}`)
}
}
}
作为call
的替代方法,您还可以使用func.apply(this, args)
。
接下来您要添加的是用于将返回值传回的return
语句:-)
我的回答与 Bergi 的基本相同:
function withTry(func){ return function(...args) { try{ // func(...args); func.apply(this, args) } catch(error){ console.log(`ERROR: ${error}`) } } } function someClass(){ this.m = null; this.s=2; } someClass.prototype.func = withTry(function(data){ console.log(this.s); }); var x = new someClass(); x.func();
我意识到,因为您正在调用x.func
,所以从withTry
返回的函数将具有正确的this
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.