JavaScript — Prototype – codeburst

  • prototype, [[Protoytype]], __proto__)/* Code 2 */function Car(name) { this.name = name;}Car.prototype.start = function() { return “engine of “+this.name + ” starting…”;};var c1 = new Car(“Santa Fe”);var c2 = new Car(“Fiesta”);c2.speak = function() { console.log(“Hello, ” + this.start());};c2.speak(); //”Hello, engine of Fiesta starting…”Let’s try to understand the above code with diagrammatic…
  • Both object is having name property and c2 is having an additional method speak() as well.But the important thing happens during the code execution is c1 and c2 gets linked with Car.prototype with internal linkage called [[Prototype]].
  • Understanding __proto__/* Code 3 */function Car(name) { this.name = name;}Car.prototype.start = function() { return “engine of “+this.name + ” starting…”;};var c1 = new Car(“Santa Fe”);var c2 = new Car(“Fiesta”);c2.speak = function() { console.log(“Hello, ” + === Car.prototype); // trueconsole.log(c1.
  • As per above prototype chain diagram, we can see object c1 does not have __proto__ property so it goes through [[Prototype]] chain to Car.prototype object but __proto__ property is not available there as well.
  • __proto__ is an public property of Object.prototype to access the [[Prototype]] is a method to access the __proto__ property.Constructor is a function, called with new keyword in front of it but .

In the below code snippet, we can see that bikeFunc() is having a prototype property inbuilt and similarly by default, object bike is having __proto__ property. In the above diagram, the right side…
Continue reading “JavaScript — Prototype – codeburst”