我正在为 node.js 开发一个网络框架。这是代码;
function Router(request, response) {
this.routes = {};
var parse = require('url').parse;
var path = parse(request.url).pathname,
reqRoutes = this.routes[request.method],
reqRoutesLen = reqRoutes.length;
..... // more code
};
我应该把所有的 var 都改成这个吗,像这样:
function Router(request, response) {
this.routes = {};
this.parse = require('url').parse;
this.path = this.parse(request.url).pathname;
this.reqRoutes = this.routes[request.method];
this.reqRoutesLen = this.reqRoutes.length;
..... // more code
};
有什么意见吗?
最佳答案
当您希望属性在相关对象的生命周期内持续存在时,将属性添加到 this
。对局部变量使用 var
。
edit — 正如 Bergi 在评论中指出的那样,用 var
声明的变量不会必然在函数调用返回时消失。它们现在并且仍然只能由声明它们的范围内的代码以及词法嵌套范围内的代码直接访问。
关于javascript - Javascript 对象中的 var 与 this,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4946625/