Tat-Yuen Hui
Tat-Yuen Hui

Reputation: 141

var vs this in Javascript object

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

};

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

};

Any comments?

Upvotes: 8

Views: 2761

Answers (4)

HoLyVieR
HoLyVieR

Reputation: 11134

Using var in the constructor is usually used for private variable while using this. is used for public variable.

Example with this. :

function Router() {
    this.foo = "bar";

    this.foobar = function () {
         return this.foo;
    }
}

var r = new Router();
r.foo // Accessible

Example with var :

function Router() {
    var _foo = "bar";

    this.foobar = function () {
         return _foo;
    }
}

var r = new Router();
r._foo // Not accessible

Upvotes: 1

Pointy
Pointy

Reputation: 413709

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

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.

Upvotes: 13

Ryan Florence
Ryan Florence

Reputation: 13483

You can think of properties hung from this sort of like instance variables in other languages (sort of).

It looks like you're creating a constructor function and will likely add some prototype methods. If that's the case, and you need access to routes, you've got it, but not path.

Router.prototype = {
  doSomething: function(){
    this.routes; // available
    path; // not available
  }
}

Upvotes: 1

Felix Kling
Felix Kling

Reputation: 816404

It on depends what you want to do.

If you declare the variables with var, then they are local to the function and cannot be accessed outside.

If you assign the variables to this, then they will be set as properties of the context object the function is called on.

So if e.g. if you write:

var obj = new Router();

then obj will have all the variables as properties and you can changed them. If you call

somobject.Router()

then all the variables will be set as properties of someobject.

Upvotes: 1

Related Questions