文件:MainApp.js
var reqHandler = reqire('HTTPRequestPostHandler')..
...
...
var httpRequestHandler = new reqHandler();
app.post('/', httpRequestHandler.handleRootPost);
<小时/>
文件:HTTPRequestPostHandler.js
HTTPRequestPostHandler =function(){
this.someVar = value;
}
HTTPRequestPostHandler.prototype.handleRootPost{
console.log(this.someVar) //Error -> this.someVar is undefined.
}
我有这两个文件。 MainApp.js 是配置 Express 和每个端点的各种处理程序的地方,例如'/'。
但是,当发生 post 请求并调用请求处理程序 (HTTPRequestPostHandler.prototype.handleRootPost) 时,我在访问变量 this.someVar 时收到未定义的错误。
为什么会发生这种情况。我在这里做错了什么。
最佳答案
这不是范围问题,而是this
问题。
通常在 JavaScript 中,this
完全由函数的调用方式设置,而不是在定义位置设置。因此,发生的情况是您将方法作为回调传递,但由于它的调用方式并未将 this
设置为您的实例。 (规范的下一个版本 ES6 将具有“箭头函数”,这些函数将 this
绑定(bind)到它们,而不是通过调用它们的方式来设置。)
在函数调用期间设置 this
的通常方法是当您将函数作为从对象检索函数引用的表达式的一部分来调用时,例如
foo.bar();
调用 bar
并将 this
设置为 foo
。但这:
var f = foo.bar;
f();
...不会。 this
将是未定义的(在严格模式下)或全局对象(在松散模式下)。
设置 this
的其他方法是通过 Function#call
和 Function#apply
,它们可以让您调用该函数并明确说明 this
应该是什么。
您可以使用bind
解决此问题:
app.post('/', httpRequestHandler.handleRootPost.bind(httpRequestHandler));
bind
返回一个函数,该函数在被调用时将调用原始函数,并将 this
设置为您作为第一个参数传入的内容。
更多(在我的博客上):
关于javascript - NodeJS、Express、原型(prototype)中的变量范围问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21020495/