var
creates a local variable that is ONLY available within the scope of the function it is declared in (the constructor in the case of your question).
this.name = xxx
assigns a property to the current object that was just created in the constructor and would be available to anyone who has a reference to that object.
Within the object constructor when it is called with the new
operator, this
is set to a newly created object of the type defined in the constructor and its prototype. So, to reference properties on that instance of the object, you MUST use this.xxx
.
So, you must use whichever of the two techniques matches what you are trying to do. There are cases for local variables in the constructor with var
and there are cases to initialize instance variables.
Here's an example of the difference:
Instance variable:
function Person(name, family) {
this.name = name;
this.family = family;
}
Person.prototype.getFull = function() {
return this.name + " " + this.family;
};
var p = new Person("Bob", "Smith");
console.log(p.name); // "Bob"
Local Variable:
function Person(name, family) {
var aName = name;
var aFamily = family;
// these variables are local and only available
// within the scope of the constructor
}
Person.prototype.getFull = function() {
// this.name and this.family are not defined
return this.name + " " + this.family;
};
var p = new Person("Bob", "Smith");
console.log(p.aName); // undefined
console.log(p.aFamily); // undefined
Extra Credit: Private Instance Variables
There is a hybrid model where you define methods within the constructor and those methods ONLY can then access the local variables within the constructor. Those variables then behave like "private" instance variables. They are not technically properties of the object, but are available to any methods defined within the constructor because of the closure created. It's a neat trick for private instance variables. Here's an example:
function Person(name, family) {
var aName = name;
var aFamily = family;
// define method within the constructor that has access to
// local variables here
this.getFull = function() {
return aName + " " + aFamily;
}
}
var p = new Person("Bob", "Smith");
console.log(p.getFull()); // "Bob Smith"
console.log(p.aName); // undefined, not instance properties
console.log(p.aFamily); // undefined, not instance properties