【问题标题】:How can I access a property of a constructor through an instance of that constructor?如何通过构造函数的实例访问构造函数的属性?
【发布时间】:2020-07-07 08:05:27
【问题描述】:

这里的构造函数是Animal。它有两个实例duck 和beagle。有一个名为eat()的函数,它实际上是Animal的原型。

function Animal() {
  this.color = "brown";
 }

Animal.prototype = {
  constructor: Animal,
  eat: function() {
    console.log("nom nom nom");
  }
};

let duck = Object.create(Animal.prototype); 
let beagle = Object.create(Animal.prototype); 
duck.eat();
console.log(duck.color);

这里

duck.eat() 

有效,但鸭子也必须继承棕色对吗?为什么我无法使用它访问它

duck.color ?

【问题讨论】:

    标签: javascript inheritance construct


    【解决方案1】:

    Animal.prototype 上没有 color 属性。它是在调用构造函数时动态添加到对象中的……但您根本没有调用构造函数。

    如果要创建类的实例,则调用构造函数。不要使用Object.create

    function Animal() {
      this.color = "brown";
     }
    
    Animal.prototype = {
      eat: function() {
        console.log("nom nom nom");
      }
    };
    
    let duck = new Animal();
    let beagle = new Animal();
    duck.eat();
    console.log(duck.color);

    【讨论】:

      【解决方案2】:

      不,它不会继承,

      请阅读Object.create的定义。

      “Object.create() 方法创建一个新对象,使用现有对象作为新创建对象的原型”

      意思是,只有prototype will be copied from existing object on will be placed in newly create object's prototype

      这里color 是实例变量而不是原型。因此在新创建的duck 对象中不可用。

      https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/create

      【讨论】:

        猜你喜欢
        • 2023-04-02
        • 2012-07-06
        • 2012-12-25
        • 2016-08-06
        • 1970-01-01
        • 1970-01-01
        • 2011-04-19
        • 1970-01-01
        • 2021-09-04
        相关资源
        最近更新 更多