您如何处理在孩子之间共享原型参考属性的问题?是否有众所周知的模式(其他然后重新定义构造函数内部的属性)来解决此问题?这根本是一个问题,还是我缺少的原型继承的东西?
示例:
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
"不完整"的模式?
感谢您的答案!
众所周知,对象的原型是包含构成该对象的基本属性的对象。与所有对象一样,该原型对象是将名称映射到值的映射。JavaScript中的数组(和对象)始终是通过参考传递的,因此,当对Object.ert.create在原型上调用时 - 仅将数组的引用复制到新对象中。正如Thez在他的评论中所说的那样,您可以做这样的事情:
function Dog(){
this.paws = ['front-right', 'front-left', 'back-right', 'back-left'];
}
Dog.prototype = {
name: 'no-name',
paws: null
};
所以我们现在可以创建我们的对象:
var rex = new Dog();
rex.name = 'Rex';
var bingo = new Dog();
bingo.name = 'Bingo';
bingo.paws.pop();
您应该查看模块模式
闭合可以使用,以便您的狗可以分开
var dog = function(){
//private
var name = "no-name";
var paws = ["front-right", "front-left", "back-right", "back-left"];
//public
function getName(){
return name;
}
function setName(newName){
name = newName;
}
function getPaws(){
return paws;
}
function pawPain(){
paws.pop();
}
//expose
return{
pawPain: pawPain,
getPaws: getPaws,
getName: getName,
setName: setName
};
};
现在您可以使用它来制作新狗
var rex = new dog();
var bingo = new dog();
rex.pawPain();
console.log(bingo.getPaws());
http://jsfiddle.net/svasp/
只需要一个构造函数。每个版本都包含自己的对象副本。
function dog(name) {
this.name = "no-name",
this.paws = ["front-right", "front-left", "back-right", "back-left"]
}
var rex = new dog();
rex.name = "Rex";
var bingo = new 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"]