将对象文字分配给原型VS将属性/函数添加到原型

时间:2014-07-03 11:51:27

标签: javascript

我有以下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()

考虑到上述代码,我的问题和观察结果是

  • 这可能的解释是什么?一旦Car.prototype被覆盖(作为参考),似乎就像链制动器(在c1和它的原型之间)。
  • C1通过c1 .__ proto
  • 维护其原型副本
  • 将对象文字分配给原型是一种很好的做法吗?
  • 我对this link进行了一些解释,但无法理解其中的大部分内容。该文章还警告Mutating [[Prototype]]

要添加,c1的构造函数非常指向新的更新原型

//create a new instance with c1 constructor
var c3 = new c1.constructor()

//will return running 3
c3.run()

0 个答案:

没有答案