Var vs this in a Javascript object

I am 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 var to this, for example:

 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?

+7
source share
4 answers

Add properties to this if you want the properties to be preserved with the life of the object in question. Use var for local variables.

edit - as Bergie notes in a comment, variables declared with var do not necessarily disappear when returned from a function call. They are available and remain available only for code in the area in which they were declared, and in lexically nested areas.

+13
source

It depends on what you want to do.

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

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

So if, for example, if you write:

 var obj = new Router(); 

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

 somobject.Router() 

then all variables will be set as someobject properties.

+1
source

You can think of properties that depend on this like instance variables in other languages ​​(sort of).

It looks like you are creating a constructor function and probably add some prototypes. If so, and you need access to routes , you got it, but not path .

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

Using var in the constructor is usually used for a private variable, and using this. used for a 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 
0
source

All Articles