NodeJS,Express,Prototyping中的变量范围问题

Err*_*lva 0 javascript prototype node.js express

文件:MainApp.js

var reqHandler = reqire('HTTPRequestPostHandler')..
...
...
var httpRequestHandler = new reqHandler();


app.post('/', httpRequestHandler.handleRootPost);
Run Code Online (Sandbox Code Playgroud)

文件:HTTPRequestPostHandler.js

HTTPRequestPostHandler =function(){
   this.someVar = value;
}
HTTPRequestPostHandler.prototype.handleRootPost{
     console.log(this.someVar) //Error -> this.someVar is undefined.

}
Run Code Online (Sandbox Code Playgroud)

我有这两个文件.MainApp.js是express配置的地方,每个端点的各种处理程序,例如'/'.

但是当发出post请求并调用请求处理程序(HTTPRequestPostHandler.prototype.handleRootPost)时,访问变量this.someVar时出现未定义的错误.

为什么会这样呢?我在这做错了什么.

T.J*_*der 5

这不是范围问题,而是一个this问题.

通常在JavaScript中,this完全由函数的调用方式设置,而不是在其定义的位置.所以正在发生的事情是你将你的方法作为回调传递,但是因为它没有以一种设置this为你的实例的方式被调用.(规范的下一个版本ES6将具有this绑定到它们的"箭头函数",而不是根据它们的调用方式设置.)

this在函数调用期间设置的常用方法是将函数作为从对象检索函数引用的表达式的一部分调用,例如

foo.bar();
Run Code Online (Sandbox Code Playgroud)

barthisset 调用foo.但是这个:

var f = foo.bar;
f();
Run Code Online (Sandbox Code Playgroud)

...... 没有.this将是未定义(在严格模式下)或全局对象(在松散模式下).

设置的其他方法this是via Function#callFunction#apply,它允许你调用函数并明确说出this应该是什么.

你可以解决这个问题bind:

app.post('/', httpRequestHandler.handleRootPost.bind(httpRequestHandler));
Run Code Online (Sandbox Code Playgroud)

bind返回一个函数,当被调用时,它将调用原始函数,并this设置为您传入的第一个参数.

更多(在我的博客上):