javascript - NodeJS、Express、原型(prototype)中的变量范围问题

标签 javascript node.js express prototype

文件: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#callFunction#apply,它们可以让您调用该函数并明确说明 this 应该是什么。

您可以使用bind解决此问题:

app.post('/', httpRequestHandler.handleRootPost.bind(httpRequestHandler));

bind 返回一个函数,该函数在被调用时将调用原始函数,并将 this 设置为您作为第一个参数传入的内容。

更多(在我的博客上):

关于javascript - NodeJS、Express、原型(prototype)中的变量范围问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21020495/

相关文章:

javascript - jQuery UI Draggable/Sortable 查找您拖动的元素

javascript - Bing Maps V8 JS API 内存泄漏问题

javascript - 如果我对当前正在下载的文件进行 XMLHttpRequest 会怎样?

javascript - 如何在 IPython Web 笔记本中使用 JavaScript 访问 "current cell output area"?

node.js - 如何在我的 Dockerfile 中添加 discovery.type=single-node

node.js - 如何使用 Passport/Facebook 策略/验证 Supertest 请求?

javascript - 带有 express Node js 服务器的 XMLhttpRequest

mysql - 如何使用 knex/Bookshelf 选择数据库表达式作为值

javascript - 如何将 NodeJS 包与 RequireJS 一起使用?

javascript - 让 Axios 在其请求中自动发送 cookie