1) this.foo = bar
The first kind you mention makes your variables properties of a (constructor) function. In JavaScript, functions are objects. Thus, using this
makes a variable a property of an object (your constructor function, in this case).
2) var x = 7
Let me start off saying that anytime you do not use var
in front of a variable (save for the this
stuff above), that variable will become a member of the global context object (window
, for most user-agents).
Thought leaders in JavaScript and programming see global variables as a sin, or code smell. Avoid global variables as much as possible.
The issue with the first method (this
) is that prior to ECMAScript 5, there was no good way to enforce privacy on object properties (as you might find in the classical C++ based languages like Java, PHP, etc). ECMAScript 5 and above allow you to assign attributes
to properties for things like writability, enumerability, etc...
However, as it pertains to var
, well, var
always makes its variables private to the function object. You cannot access a var variable from external, client code like this
dog.age = 5 //Trying to assign the number five to a var variable.
You can make a function that has access (known as an accessor), though. In effect, when you see var
, think private to this object's scope. That's the gist of it. Closure (from enclosure) is an important subject in JavaScript. When you get into using var
, inevitably you start to learn about closure.
3) No key word.
Finally, using naked variables attaches all of them to the global object (window
, for most user-agents). This tends to lead to confusion and debugging issues. You may inadvertently stage a collision or conflict where a value is being changed across many instances of your constructor function. It's just not the way to go.
In summary, a fantastic book on the subject of JavaScript variables is The Principles of Object Oriented JavaScript. Mr. Zakas explains things much better than Crockford and Flannagan. I highly recommend it. Know your goal. Know your problem. Avoid global variables. Learn about JavaScript's object mode and scope. I recommend JavaScript: The Definitive Guide when it comes to learning about scope and context in JavaScript.