Reputation: 7612
I am learning javascript. I am confused between the following two notations where the newly created objects inherit the properties. How are they different and when should i use them?
Code 1:
var Vehicle = function Vehicle() {
this.wheel=2
}
var vehicle = new Vehicle();
alert(vehicle.wheel);
Code 2:
var Vehicle = function Vehicle() {
}
Vehicle.prototype.wheel = 4;
var vehicle = new Vehicle();
alert(vehicle.wheel);
When is the keyword prototype
used?
Upvotes: 3
Views: 124
Reputation: 576
You need to read about prototype, there were lots of threads in stackoverflow, do a little search. For example read this article. Or grab a book which is the best approach to learn something, I recommend this great book, JavaScript: The Good Parts
In general it's much better using prototype in terms of memory consumption and prototype chain that can be extendable.
Upvotes: 0
Reputation: 1153
Properties defined on prototype will be shared by all the instances. So if you create 10 vehicles, they just share the wheel property(only one), and each vehicle doesn't have a wheel property on itself.
Upvotes: 4
Reputation: 30187
The most important difference is that when you add a property to the prototype of a function and instantiate a new object from it, that property is accessed in the new object by stepping up the inheritance chain rather than it being directly on the object.
Upvotes: 2