如何解决如何将其与高阶函数绑定
我在某些文件中具有此高阶功能
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
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。