1

我已经阅读了很多关于原型继承如何工作以及解释器如何遍历原型链来查找属性的内容。

function Man()
{
    this.hands=2;//1
}
function father()
{
    this.name="";
}
father.prototype= new Man();//2

var malay= new father();
var abhik= new father();

现在我的问题是语句 #1 & #2 只被调用一次。那么“abhik”和“malay”应该共享同一个 Man 对象吗?所以内存中会有 3 个对象。1.abhik 2.malay 3.man (一个实例由两者共享)所以按照这种逻辑,更改的值应该在对象之间共享?

malay.hands=3;
console.log(abhik.hands);
abhik.hands=4;
console.log(malay.hands);

但事实并非如此。为什么这样 ?

4

2 回答 2

2

您的理解是正确的,有 3 个对象,并且两者都abhik继承malay自同一个Man实例。但是当你在和对象上设置新hands属性时,你给了它们自己的属性,它们不再从原型继承属性。malayabhikhandshandsMan

插图:

在您第一次创建malayand之后abhik,这里是您的三个对象的模拟:

father.prototype -> {hands: 2} 
malay -> {name: ""}   // Empty name property, NO hands property
abhik -> {name: ""}   // Empty name property, NO hands property

当您检查or上的hands属性时,解释器会看到没有这样的属性,并会检查原型链并发现它们的父级确实有一个属性,因此解释器将报告该值,即.malayabhikfather.prototypehands2

设置hands属性后,您的对象如下所示:

father.prototype -> {hands: 2} 
malay -> {name: "", hands: 3}   // Empty name property, OWN hands property
abhik -> {name: "", hands: 4}   // Empty name property, OWN hands property

现在您的对象都有自己的hands属性。

资源:这是一篇写得很好的(但很长)关于 javascript 继承的文章:http: //manuel.kiessling.net/2012/03/23/object-orientation-and-inheritance-in-javascript-a-comprehensive-解释/

于 2013-05-23T04:55:14.063 回答
1

如果您需要在实例之间共享原始类型或不可变类型,您可以使用闭包来保留它的值并使用 getter 和 setter 来访问它。

function Man()
{
  var hands=2;
  return {
    getHands:function(){
      return hands;
    },
    setHands:function(number){
      hands=number;
    }
  }
}
function Father(name)
{
    this.name=name;
}
Father.prototype= Man();
malay=new Father("malay");
abhik=new Father("abhik");
malay.setHands(4);
console.log(abhik.getHands());
console.log(malay.getHands());

如果您需要 Father 成为 Man 的实例,您可以执行以下操作:

function Hands(){
  var hands=2;
  return {
    get:function(){
      return hands;
    },
    set:function(number){
      hands=number;
    }
  }
}

function Man(){
  this.age=18;
  this.array=[];
}
Man.prototype.hands=Hands();
function Father(name){
    //take ownership (copy) of every variable
    //defined in the Man function body
    //with this.... prototype defined
    //are still shared among instances
    Man.call(this);
    this.name=name;
}
Father.prototype= new Man();


malay=new Father("malay");
abhik=new Father("abhik");
malay.hands.set(4);
console.log(abhik.hands.get());
console.log(malay.hands.get());
malay.age=34;
console.log(abhik.age);//from Man.age
console.log(malay.age);//from malay.age
delete malay.age;
console.log(malay.age);//from Man.age
malay.array.push(22);
console.log(abhik.array);// is [] but would be [22]
 // if Man.call(this) was not in the Father function
console.log(malay instanceof Man);
于 2013-05-23T05:18:18.647 回答