Javascript 在这种情况下,为什么绑定函数对NodeJS停止工作
为什么bind函数对以下代码停止工作Javascript 在这种情况下,为什么绑定函数对NodeJS停止工作,javascript,node.js,function,bind,Javascript,Node.js,Function,Bind,为什么bind函数对以下代码停止工作 function exitHandler(options, err) { console.log('exit'); if (options.cleanup) console.log('clean'); if (err) console.log(err.stack); if (options.exit) process.exit(); } //do something when app is closing //process.on('exi
function exitHandler(options, err) {
console.log('exit');
if (options.cleanup) console.log('clean');
if (err) console.log(err.stack);
if (options.exit) process.exit();
}
//do something when app is closing
//process.on('exit', exitHandler.bind(null,{cleanup:true})); process.exit()
// or
process.on('exit', function() {
exitHandler.bind(null,{cleanup:true})
});
如果我取消对
进程的注释('exit',exitHandler.bind…
行,它会工作得很好。我认为这是因为绑定创建了一个新函数,所以在第二个示例中,它实际上不会触发函数。在第一个示例中,它确实会被触发。我认为这是因为绑定创建了一个新函数,所以在第二个示例中,它实际上不会触发函数。在第一种情况下,它确实会被解雇。你确定它是bind
而不是call
你想要的:
function exitHandler(options, err) {
console.log('exit');
if (options.cleanup) console.log('clean');
if (err) console.log(err.stack);
if (options.exit) process.exit();
}
process.on('exit', function() {
exitHandler.call(null,{cleanup:true})
});
编辑:
如果未使用上下文(this
),则可以正常调用该函数:
exitHandler({cleanup:true});
您确定它是
bind
而不是call
您想要的:
function exitHandler(options, err) {
console.log('exit');
if (options.cleanup) console.log('clean');
if (err) console.log(err.stack);
if (options.exit) process.exit();
}
process.on('exit', function() {
exitHandler.call(null,{cleanup:true})
});
编辑:
如果未使用上下文(this
),则可以正常调用该函数:
exitHandler({cleanup:true});
.bind
实际上并不调用该函数(即….call
),它只是将其绑定,适当地设置this
。在注释的情况下,您将绑定函数作为回调传递;在第二种情况下,您将其包装在另一个匿名函数中,但从不调用绑定函数。为什么不只使用注释的版本呢?或者,假设您在this
de>exitHandler(并显式将其设置为null
),根本不绑定它?。bind
实际上不调用函数(即…。调用
),它只是将其绑定,适当地设置this
。在注释的情况下,您将绑定函数作为回调传递;在第二种情况下,您将其包装在另一个匿名函数中,但从不调用绑定函数。为什么不只使用注释的版本呢?或者,假设您在this
de>exitHandler(并将其显式设置为null
),根本不绑定它?或者干脆exitHandler({cleanup:true})
因为这个参数无论如何都不会被使用。@doodlemeister,你说得对,但是,只要技术上允许,我会尽量接近OP的功能correct@doodlemeister,不是真的。这是我尝试的第一件事,我得到了if(options.cleanup)…TypeError:无法读取null的属性“cleanup”
。有人知道为什么吗?@xpt听起来像是在执行exitHandler(null,{cleanup:true})
?或者只是exitHandler({cleanup:true})
因为这个参数无论如何都不会被使用。@doodlemeister,你说得对,但是,只要技术上允许,我会尽量接近OP的功能correct@doodlemeister,不是真的。这是我尝试的第一件事,我得到了if(options.cleanup)…TypeError:无法读取null的属性“cleanup”
。有人知道为什么吗?@xpt听起来像是你在做existhandler(null,{cleanup:true})
?感谢你的明确解释,对我这样的无名小卒!我要到6分钟后才能接受答案…顺便说一句,想知道的人“为什么不坚持评论版本?”,因为我添加了更多的代码,显然,它是从OP中删除的,以减少分心。感谢你的明确解释,对于像我这样明显的noob!我不能接受答案,直到6分钟后…顺便说一句,对于想知道“为什么不坚持评论版本?”?“,因为我添加了更多的代码,显然,它是从OP中删除的,以减少干扰。