【问题标题】:does inheriting from another constructor overridedes the existing properties from the prototype chain of the constructor that inherits从另一个构造函数继承会覆盖继承的构造函数原型链中的现有属性
【发布时间】:2014-09-14 09:20:41
【问题描述】:

这里我有两个构造函数,分别是 First 和 Second。

First 继承自 Second。First 在其原型链上也有一个 hair 属性。

一个新创建的对象 tom 应该是 First 构造函数的一个实例,它还有一个用户定义的属性,称为 nail。

如果我想使用 for...in 循环记录 tom 对象的所有可枚举属性,它只显示名称、指甲和年龄。但是头发属性似乎从其原型链中消失了。

为什么头发属性从原型链中消失了?怎么找回来??

<html>
<body>
<script>
   function First(name){
       this.name=name;
   }
   First.prototype.hair='black';// tom.hair gets me undefined
   function Second(){
       this.age=1;
   }

   First.prototype=new Second();
   var tom=new First('tom');
   tom.nail='sharp';// added property to tom
   for(var i in tom){
       console.log(i);
   }
   console.log(tom.hair);
</script>
</body>
</html>

【问题讨论】:

  • 您可能希望通过调用 Second.call(this) 来重新使用 Second 构造函数并使用 Object.create 而不是创建 Second 的实例以用作 First.prototype,因为现在您正在混淆共享和实例特定成员(年龄)在此处获取更多信息:stackoverflow.com/questions/16063394/…

标签: javascript


【解决方案1】:

你覆盖了prototype

First.prototype=new Second();

做起来

First.prototype.age=new Second().age;

它有效。

JSFIDDLE.

【讨论】:

  • 这个说法不清楚 First.prototype.age=new Second();你能详细说明你的答案吗。我的意思是为什么它有效??
  • 当您开始First.prototype=new Second(); 行时,您将覆盖整个prototype 对象。还有.prototype.hair.hair 不再存在,因为您说的是 prototype={}
  • 第一部分是正确的,但解决方案不正确 - age 属性现在是一个对象,而不是 1
  • 您的新日志向您显示了一个具有age 属性的Second 对象1,它应该只显示1。如果你console.log(tom.age.age),你会得到1,而你应该得到undefined。基本上,您的解决方案不是设置新原型,而是向现有原型添加一个属性,这不是 OP 试图实现的目标
  • 有趣的解决方案。学到了一些新的逻辑:)
【解决方案2】:
First.prototype.hair 

之前声明
First.prototype 

Second构造的对象的实例覆盖

First.prototype=new Second(); 

被调用。要将hair 属性添加到First 的原型中,请在分配通过调用Second 创建的对象的实例后将其添加到原型中,即

function First(name){
    this.name=name;
}

function Second(){
    this.age=1;
}

First.prototype=new Second();

// add to prototype after overwriting/assigning prototype above
First.prototype.hair='black';

var tom=new First('tom');
tom.nail='sharp';

for(var i in tom){
    console.log(i);
}

【讨论】:

    【解决方案3】:

    问题是您在First 的默认原型上设置了hair 属性,然后将其替换为新原型,这意味着您的原始原型丢失了。如果您像这样重新排序语句,它将起作用:

    function First(name){
        this.name=name;
    }
    function Second(){
        this.age=1;
    }
    
    First.prototype=new Second();
    First.prototype.hair='black'; // this works now!
    
    var tom=new First('tom');
    tom.nail='sharp';// added property to tom
    for(var i in tom){
        console.log(i);
    }
    console.log(tom.hair);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-01-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-06-01
      相关资源
      最近更新 更多