在Javascript对象中var vs this [英] var vs this in Javascript object

查看:134
本文介绍了在Javascript对象中var vs this的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在为node.js开发一个web框架。这是代码;

I'm developing a web framework for node.js. here is the code;

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更改为此,如下所示:

Should I change all the var to this, like so:

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

};

有任何意见吗?

推荐答案

如果希望属性在相关对象的生命周期中保持不变,则将属性添加到。对局部变量使用 var

Add properties to this when you want the properties to persist with the life of the object in question. Use var for local variables.

编辑—正如Bergi在评论中指出的那样,用 var 声明的变量在从函数调用返回时不会必然消失。它们是,并且只能直接访问声明它们的范围内的代码,以及词汇嵌套的范围。

edit — as Bergi notes in a comment, variables declared with var don't necessarily vanish upon return from a function invocation. They are, and remain, directly accessible only to code in the scope in which they were declared, and in lexically nested scopes.

这篇关于在Javascript对象中var vs this的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆