If I have a constructor and want to add additional properties to it, which should I use? constructorName.nameofProperty or constructorName.prototype.nameofProperty? What's the difference?
2 Answers
If you look at the console output from the below snippet, you'll see that adding something to an objects prototype adds it to all instances of the constructor. Both Jill and Tim now have a setAge method, but only Jill has actually set her age. Also, something added directly to the constructor does not inherit to instances.
function Person(firstName, lastName) {
this.firstName = firstName;
this.lastName = lastName;
}
var Tim = new Person("Tim", "Dawson");
var Jill = new Person("Jill", "Swanson");
Person.prototype.setAge = function(age) {
this.age = age;
}
Jill.setAge(28);
Person.doesThisInherit = function() {
console.log("No it doesn't");
}
var Sam = new Person("Sam", "Testy");
console.log(Tim);
console.log(Jill);
console.log(Sam);
Comments
It depends.
Do you want the object returned from the constructor function to have those properties? If so, you need to augment that property to the object returned from the constructor function:
var constructorFunction = function () {
this.someProperty = someValue;
}
Do you want to add properties to the constructor function (remember functions are objects so you can add properties to them)? If so, do
constructorName.someProperty = someValue
I don't think that is what you want though. That does not effect on objects returned from the constructor function. It just adds a property to the function.
You could attach the property to the prototype if you want. That would mean that all objects constructed with that function (if you invoke it with the 'new' prefix) would have a reference to that property via its prototype chain. This would mean that each of those objects would not have their own copy of the property but would all reference the same one. That is, the one attached to the constructor function's prototype object. This could save you memory if that is a concern. If not, it may be best for each object to have it's own copy of that property, which is what the first example does. That way, changing the property on one of the objects does not affect the other objects created from that same constructor function.