I have following JavaScript code
var Car = function(){}
var c1 = new Car();
//Will throw an error as there is no run function
//c1.run()
//add run function to Car Prototype
Car.prototype.run = function() { return "running 1."};
//will return "running 1."
c1.run()
//Modify the run function
Car.prototype.run = function() { return "running 2."}
//will return running 2
c1.run()
//will return true
c1 instanceof Car
//Assign multiple functions via object literal
Car.prototype = {
run : function() { return "running 3."},
openDoors : function() { return "opening doors."}
}
//c1.run still returning running 2
c1.run()
//returns false, c1 no longer connected to Car
c1 instanceof Car
//a new instance of Car will correctly point to
//functions from updated prototype
var c2 = new Car()
//will return running 3
c2.run()
//C1 do not have "openDoors" method
//c1.openDoors()
//openDoors for C2 works
c2.openDoors()
Considering above code my questions and observations are
- What is possible explanation of this? Seems like chain brakes (between c1 and its prototype) as soon as Car.prototype was overridden (as its a reference).
- C1 maintains its copy of prototype via c1.__proto
- Is it a good practice of assigning object literals to prototype?
- I refereed this link for some explanation, but could not grasp most of it. The article also warns about Mutating [[Prototype]]
To add, the constructor of c1 is very well pointing to new updated prototype
//create a new instance with c1 constructor
var c3 = new c1.constructor()
//will return running 3
c3.run()