javascript object declaration using prototype(including case) -
possible duplicate:
use of 'prototype' vs. 'this' in javascript?
i donot know why developer use javascript prototype object exactly. so, made sample code below. 1 using prototype object, other plain syntax. difference btwn 2 of them? there benefit use prototype syntax, 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());
yes, there difference. using prototype
, property or method declared once in object , same instances. using direct properties/methods, these properties , method added every instance of object. here's car constructor:
function car(){this.engine = 'no known engine'}; car.prototype.setengine = function(val){ this.engine = val; }
now method setengine
equal instances of car, engine
property can vary per instance. prototypal methods defined once , looked via prototype chain (see this). in case setengine
sets 'engine' property of the current instance of car. 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'
Comments
Post a Comment