poorvank
poorvank

Reputation: 7612

What is the difference between the following two declarations and when should they be used

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

Answers (3)

lastboy
lastboy

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

grape_mao
grape_mao

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

sushil bharwani
sushil bharwani

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

Related Questions