如何解决JavaScript绑定此,而无权访问类
我无法在不对类本身进行一些修改的情况下访问类的方法。
请参阅以下演示代码:
function myCallback() {
this.otherMethod();
}
class hiddenClass {
static hiddenFunction(callback) {
callback();
}
static otherMethod(){
console.log("success");
}
}
hiddenClass.hiddenFunction(myCallback);
在这个简单的示例中,我想在回调中访问this.otherMethod()。显而易见的答案是将callback()
更改为callback.bind(this)()
,但是在这种情况下,hiddenClass将是一个库。
如何调用此其他方法?
作为参考,我正在尝试使用node-cron创建cron作业。如果数据库检查返回true,则我想销毁这些作业,检查作业的每个周期(在回调中)。作业具有内部方法.destroy()
。我知道我可以将cron作业保存在一个变量中,然后调用variable.destroy()
,但是有没有一种方法可以在回调中完成(因为这些作业是在for循环中创建的,所以我不想指出从回调内部销毁哪一个)
cron.schedule(`5 * * * * *`,async function () {
schedule = await Schedule.findById(schedule._id);
if (!schedule) this.destroy() // Destroy the job if schedule is not found (this returns Window)
}
);
解决方法
您的推理是合理的,您需要将回调绑定到相关的类。但是,可以通过修改对hiddenFunction的调用,在示例代码中完成此操作:
hiddenClass.hiddenFunction(myCallback.bind(hiddenClass));
这不需要修改库。
至于您的参考代码...
ES2015之前的方法是创建一个匿名函数,该匿名函数通过使用当前循环迭代的值进行调用来绑定,例如:
var schedules = [1,2,3,4,5];
for(var i=0;i<schedules.length;i++){
setTimeout(function(){console.log(schedules[i])},10);
}
/* => outputs:
5
5
5
5
5
*/
for(var i=0;i<schedules.length;i++){
// create an anonymous function with the first arg bound at call time
(function(j){
setTimeout(function(){console.log(schedules[j])},10);
}(i));
}
/* => outputs:
1
2
3
4
5
*/
但是,在您的代码中这是不可能的,因为您尝试传递匿名回调并在所述函数中引用当前循环的迭代值,要求匿名函数在知道cron.schedule
的返回值之前本身会传递给cron.schedule
。
该问题的解决方案是在循环中使用let
或const
来绑定当前迭代的值。它们是块作用域的,而不是词法作用域的,因此它们在每次迭代时都保留值,导致N个闭包相同的匿名函数。我们可以在以下循环中演示两者之间的区别:
for(var foo of [1,5]){
const bar = foo;
(async function(){
await Promise.resolve().then(()=>console.log({bar,foo}));
}());
}
/* outputs:
{ bar: 1,foo: 5 }
{ bar: 2,foo: 5 }
{ bar: 3,foo: 5 }
{ bar: 4,foo: 5 }
{ bar: 5,foo: 5 }
*/
将它们组合在一起,您的循环调度器将如下所示:
for(let schedule of schedules){
const me = cron.schedule(`5 * * * * *`,async function () {
// the value of `me` is bound to each iteration and you can refer to it as needed
schedule = await Schedule.findById(schedule._id);
if (!schedule) me.destroy();
});
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。