【问题标题】:Constructor property of an object对象的构造函数属性
【发布时间】:2018-06-11 22:44:36
【问题描述】:

我在阅读原型时遇到了这个例子。

function Animal(){
    this.name = 'Animal'
}

var animal1 = new Animal();

function Rabbit(){
    this.canEat = true;
}

Rabbit.prototype = new Animal();

var r = new Rabbit();

console.log(r.constructor)

控制台将 Animal 作为 r.constructor 的输出,这有点令人困惑,因为构造函数属性应该返回 Rabbit,因为 r 是通过使用 new 运算符调用 Rabbit 创建的。

另外,如果我在分配原型之前调用 Rabbit 函数,它会给我想要的结果。

【问题讨论】:

  • 在制作对象之前你必须做Rabbit.prototype.constructor=Rabbit;
  • 在分配原型时,将构造函数更改为继承自Animal的构造函数。
  • 为什么会这样?构造函数是原型的属性还是对象的属性?
  • constructor 继承自原型。
  • 你现在明白为什么r.constructor返回Animal了吗?

标签: javascript prototype


【解决方案1】:

对象从其原型继承constructor(通常);他们从构造函数的prototype 属性中获取原型,该属性在创建它们时创建它们(如果它们是由构造函数创建的)。 Rabbit.prototype 的 constructor 不正确,因为:

Rabbit.prototype = new Animal();

调用Animal 创建一个新实例,并将该实例分配为Rabbit.prototype。所以它的constructor,继承自Animal.prototype,是Animal。您已替换以前位于 Rabbit.prototype 上的默认对象(将 constructor 设置为 Rabbit)。

一般来说,Rabbit.prototype = new Animal() 并不是设置继承的最佳方式。相反,您可以这样做:

Rabbit.prototype = Object.create(Animal.prototype);
Rabbit.prototype.constructor = Rabbit;

然后在Rabbit:

function Rabbit() {
    Animal.call(this);    // ***
    this.name = "Rabbit"; // Presumably we want to change Animal's deafult
    this.canEat = true;
}

那里有三个变化:

  1. 在设置继承时我们不调用Animal,我们只是创建一个以Animal.prototype为原型的新对象,并将其放在Rabbit.prototype上。
  2. 我们在分配给Rabbit.prototype 的新对象上设置了constructor。
  3. 我们确实在初始化实例时调用Animal(在Rabbit中)。

现场示例:

function Animal(){
    this.name = 'Animal'
}

var animal1 = new Animal();

function Rabbit() {
    Animal.call(this);    // ***
    this.name = "Rabbit"; // Presumably we want to change Animal's deafult
    this.canEat = true;
}

Rabbit.prototype = Object.create(Animal.prototype);
Rabbit.prototype.constructor = Rabbit;


var r = new Rabbit();
console.log(r.constructor);

或者,当然,使用 ES2015+ class 语法,它会为您处理这个管道(以及其他一些好处)。

class Animal {
    constructor() {
        this.name = "Animal";
    }
}

class Rabbit extends Animal {
    constructor() {
        super();
        this.name = "Rabbit";
        this.canEat = true;
    }
}

const r = new Rabbit();
console.log(r.constructor);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2010-10-07
    • 1970-01-01
    • 1970-01-01
    • 2014-01-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多