3

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?

poorvank
  • 7,524
  • 19
  • 60
  • 102
  • Maybe this will help: http://stackoverflow.com/questions/16063394/prototypical-inheritance-writing-up/16063711#16063711 – HMR Sep 18 '13 at 09:03

3 Answers3

4

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.

grape_mao
  • 1,153
  • 1
  • 8
  • 16
2

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.

sushil bharwani
  • 29,685
  • 30
  • 94
  • 128
0

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.

lastboy
  • 566
  • 4
  • 12