I’m Codeyear fellow and unfortunately prototype object concept is not explained.I google it and found tutorial. After learning,my understanding says that we use prototype object inheritance to save memory and share common properties between objects . am i right ? if yes , dont you think the below code is the bad practice. Since car constructor has already defined price,speed and & getPrice,why we need to define same thing again,since we are using the concept of inheritance . please explain . below is the code .
function Car( listedPrice ) {
var price = listedPrice;
this.speed = 0;
this.getPrice = function() {
return price;
};
}
Car.prototype.accelerate = function() {
this.speed += 10;
};
function ElectricCar( listedPrice ) {
var price = listedPrice;
this.speed = 0;
this.getPrice = function() {
return price;
};
}
ElectricCar.prototype = new Car(); // Please also explain why car constructor
// is not thowing error since we are not passing
// listedPrice parameter
myElectricCar = new ElectricCar(500);
console.log(myElectricCar instanceof Car);
The constructor and the prototype are two separate concepts. When you apply the prototypal inheritance with
ElectricCar.prototype = new Car();, it inherits only the methods defined on the object and its prototype, not the constructor itself.You can actually see the way this works with some quick
console.log()calls:This returns:
The first line is the constructor.
The second is the actual prototype, as set by
ElectricCar.prototype = new Car();above. Remember that in the constructor ofCar,this.speedandthis.getPricewere set, which explains the values ofElectricCar.prototype.speedandElectricCar.prototype.getPrice.What is perhaps least clear is the last line, the
ElectricCar.prototype.__proto__. This is the prototype of the prototype.Carobjects have aprototypeobject in whichacceleratewas defined. This prototype is copied over to the prototype ofElectricCarin its internal__proto__property. This is called prototype chaining.Because the constructor is not part of the prototype, and the prototype is all you’re inheriting, the constructor for
Carhas been copied and pasted intoElectricCar. As you point out, there are definitely cleaner ways to do this. Here’s an alternative:See
applyfor more details.As for your final question (why doesn’t
new Car()throw an error), as the other answers say, that’s kind of how JavaScript works. If you supply fewer arguments to a function than it has parameters, any unset (so to speak) parameters will be set toundefined. To demonstrate:This will return:
As you can see
undefinedis actually a variable that you can pass around (as inreturnMe(undefined)). For more on this, seeundefined.