我有以下JavaScript代码
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()
考虑到上述代码,我的问题和观察结果是
要添加,c1的构造函数非常指向新的更新原型
//create a new instance with c1 constructor
var c3 = new c1.constructor()
//will return running 3
c3.run()