我试图用一个特定的require对象从一个this d节点模块调用一个方法。据我所见,有三种方法可以通过.bind(obj)(args)、.call(obj, arg1, ...)或.apply(obj, aryArgs)来实现。我目前正在使用bind,但我尝试了这三种方法,但都没有成功。
这就是我打电话的地方:
var library = require("./library.js");
// ...
requestHandler.bind(library)(req);requestHandler是对此文件中导出的status函数的引用:
exports.status = () => {
console.log(this);
this.render({text: "status ok"});
};
exports.paramSwitching = () => {
this.render("rendered via param switching");
};
exports.json = () => {
this.render({json: {this: 'renders', as: 'json'}});
};
exports.view = () => {
this.render({view: true, locals: {text: 'hi'}});
};我希望这样做能够使status函数以library作为其this对象进行调用,因为这是定义render的地方。但是,console.log语句将this显示为保存status的文件的计算内容,即
{ status: [Function],
paramSwitching: [Function],
json: [Function],
view: [Function] }这里发生了什么,我该怎么解决?(或者,如果我做不到,因为Node做了一些奇怪的事情,有什么办法吗?)
发布于 2017-03-24 12:15:00
您的请求处理程序使用箭头符号声明:
exports.status = () => {
console.log(this);
this.render({text: "status ok"});
};通过设计,箭头符号在函数声明时捕获this。就好像是你干的那样:
exports.status = (function(){
console.log(this);
this.render({text: "status ok"});
}).bind(this);这意味着status()函数已经绑定,不能反弹。解决方案是停止使用箭头函数:
exports.status = function(){
console.log(this);
this.render({text: "status ok"});
};发布于 2017-03-24 12:14:42
箭头函数本身已经将函数体函数中的this绑定到它在其中定义的上下文的this。因此,您不能使用任何这些方法来更改this。
如果需要更改this,则不能使用箭头函数。
发布于 2017-03-24 12:16:18
我刚发完这个问题就想出来了。我在包含status的文件中使用了箭头函数, scope使用这个箭头函数,但是使用了封闭的上下文。
对这些函数调用bind、call或apply没有任何效果,因为this已经设置为函数的封闭上下文,在本例中,该上下文是eval'd文件。
将箭头函数切换到常规函数(将() =>更改为function ())已经解决了这个问题。
https://stackoverflow.com/questions/42999152
复制相似问题