0

Possible Duplicate:
Use of 'prototype' vs. 'this' in Javascript?

I donot know why some developer use javascript prototype object exactly. so, I made a sample code below. one using prototype object, the other plain syntax. what is difference btwn two of them? Is there any benefit to use prototype syntax, the first case?

Car.prototype.engine_ = 'bmw';
Car.prototype.getEngine = function(){
  return this.engine_;
}
Car.prototype.setEngine = function(engine){
  this.engine_ = engine;
}
function Car(){

//....

}

    var myCar = new Car();
    myCar.getEngine();
    myCar.setEngine('benz');
    console.debug(myCar.getEngine());

vs

function Car(){
  this.engine_ = 'bmw';
  this.setEngine = function(engine){
    engine_ = engine;
  }
  this.getEngine = function() {
    return engine_;
  }

  //...

}

var myCar = new Car();
myCar.getEngine();
myCar.setEngine('benz');
console.debug(myCar.getEngine());
Community
  • 1
  • 1
Jinbom Heo
  • 7,248
  • 14
  • 52
  • 59
  • 1
    duplicate: http://stackoverflow.com/questions/310870/use-of-prototype-vs-this-in-javascript – Tom Tu Feb 18 '11 at 10:09

2 Answers2

1

Yes, there is a difference. Using prototype, your property or method is declared once in the Object and the same for all instances. Using direct properties/methods, these properties and method are added to every instance of the Object. So here's your Car constructor:

function Car(){this.engine = 'no known engine'};
Car.prototype.setEngine = function(val){
  this.engine = val;
}

Now the method setEngine is equal to all instances of your Car, but the engine property can vary per instance. The prototypal methods are defined once and looked up via the prototype chain (see also this). In this case setEngine sets the 'engine' property of the current instance of your Car. So you can do:

var bmw = new Car, merc = new Car;
bmw.setEngine('BMW');
merc.setEngine('Mercedes');
console.log(bmw.engine); //=> 'BMW'
console.log(merc.engine); //= 'Mercedes'
KooiInc
  • 119,216
  • 31
  • 141
  • 177
0

AFAIK there is no difference between this ones

SergeS
  • 11,533
  • 3
  • 29
  • 35
  • 1
    you know wrong my dear friend - http://stackoverflow.com/questions/310870/use-of-prototype-vs-this-in-javascript time to catch up on fundamentals behind the language! :) – Tom Tu Feb 18 '11 at 10:22