【问题标题】:Surrogate instance changing classes when creating prototypal inheritance?创建原型继承时代理实例更改类?
【发布时间】:2021-01-06 17:30:12
【问题描述】:

所以我正在尝试使用代理方法设置原型继承,但我遇到了一种对我来说似乎很奇怪的行为。这是我的课程:

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

Animal.prototype.eat = function() { 
    console.log("mmm... food...")
};

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

var Surrogate = function() {}
Surrogate.prototype = Animal.prototype;

现在,我想将 Animal 设置为基类。如果我创建一个代理实例:

浏览器控制台说 s 是 Surrogate 的一个实例。

但是,当我将 Dog 类的原型设置为 Surrogate 的实例时:

它变成了 Animal 的一个实例?为什么会这样?这是正确的还是我解释错了?

【问题讨论】:

  • Surrogate 是 Animal 的一个实例,因此 Dog 对调试器来说也应该是 Animal 的一个实例

标签: javascript prototypal-inheritance


【解决方案1】:

使用代理方法

Protip:使用Object.create,这已经是十年来的标准:-)

它变成了 Animal 的一个实例?

没有。它仍然是完全相同的对象,并且没有更改任何功能。这是一个instanceof Animal,就像以前一样。

您在控制台中看到的Animal {} 是调试器的自定义显示选项。

为什么会这样?

我的猜测是您会看到 internal optimisation that occurs when an object is assigned as the .prototype of a function 的副作用,它只能在调试器中观察到。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-12-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多