您如何处理在其子代之间共享原型的引用属性的问题?是否有任何众所周知的模式(除了在构造函数中重新定义属性)来解决这个问题?这到底是个问题,还是我缺少关于原型继承的一些东西?
例子:
var dog =
{
name: "no-name",
paws: ["front-right", "front-left", "back-right", "back-left"]
};
var rex = Object.create(dog);
rex.name = "Rex";
var bingo = Object.create(dog);
bingo.name = "Bingo";
bingo.paws.pop(); //Bingo is just like a dog, but has lost a paw in a tragic accident
console.log(bingo.paws); //["front-right", "front-left", "back-right"]
console.log(rex.paws); //Rex lost a paw too! ["front-right", "front-left", "back-right"]
更新:
在研究了原型继承之后,在我看来,这种范式中“自然”的编程方式是扩展对象,而不是在将它们用作“类”的意义上过分依赖构造函数。我在博客上看到的示例(它似乎也与 Douglas Crockford 的一致Object.create
)或多或少是这样的:
var Dog =
{
name: "no-name",
paws: ["front-right", "front-left", "back-right", "back-left"],
bark: function() { alert("Bark!!"); }
};
//No constructor acting like a "class"
var BigDog = Object.create(Dog);
BigDog.bark = function() { alert("WOLF!!!"); };
var thor = Object.create(BigDog);
thor.name = "Thor";
thor.bark();
构造函数是在新实例上复制或创建新数组的唯一方法吗?这是Object.create
“不完整”的模式吗?
感谢您的回答!