var vs this in Javascript object
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.
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
.