0

what is the difference between adding a method as a prototype and defining inside the constructor function

For eg: between

function Car( model, year, miles ) {
this.model = model;
this.year = year;
this.miles = miles;
this.toString = function () {
         return this.model + " has done " + this.miles + " miles";
};
}

and

function Car( model, year, miles ) {
this.model = model;
this.year = year;
this.miles = miles;
}

Car.prototype.toString = function () {
        return this.model + " has done " + this.miles + " miles";
};
Prats
  • 1,635
  • 4
  • 23
  • 28

1 Answers1

1
  1. this.toSting adds a property to each new object made using the Car constructor.

  2. Car.prototype is a separate object where all objects made using new Car(...) inherit properties from. Because toString is a property of the prototype object, this is inherited by all Car objects.

Let var car = new Car(...);

Both are accessed by calling car.toString().

However when the call is made, car is first searched for the toString property. If none exists, then the prototype is searched for toString and that is called instead. If neither exist, then the prototypes prototype is searched all the way up the chain until toString is found on the base objects prototype.

puqeko
  • 321
  • 2
  • 9
  • new car delegates to the prototype. ;-) – synthet1c Dec 30 '15 at 07:57
  • @synthet1c If the inheritance of a property through the prototype chain is conditional on whether or not said property is found on the object, can this still be clarified as delegation? I agree inheritance is not the best term. – puqeko Dec 30 '15 at 08:08