【发布时间】:2021-02-24 13:05:02
【问题描述】:
我创建了一个示例来说明:
// this is the parent class
function animal() { console.log('animal constructor') }
// allow animals to walk
animal.prototype.walk = function() { console.log('animal walking') }
// create child class
function cat() { console.log('cat constructor') }
// cat inherits from animal
cat.prototype = Object.create(animal.prototype);
// let cats meow
cat.prototype.meow = function() { console.log('meow') }
// create a cat object
var myCat = new cat();
/* output: cat constructor */
// yet, the constructor that ran is different than what the prototype for cat reports
console.log(cat.prototype.constructor);
/* output: function animal() { console.log('animal constructor') } */
所以请注意继承是如何按预期工作的,cat 从其父 dog 类继承方法“walk”,并向子类添加更多方法(如 meow)按预期工作。但是,当我创建 cat 的实例时, cat 的构造函数运行,而 cat.prototype.constructor 指向从 dog“继承”的构造函数。
object.prototype.constructor 的目的不就是允许我们在声明对象后修改对象的构造函数而不清除对象的原型吗?在上面的例子中,存储在 cat.prototype.constructor 中的构造函数不应该指向创建 cat 对象时运行的同一个构造函数吗?这种明显的歧义是否与this source code 中此语句的运行方式有关:
// Enforce the constructor to be what we expect
Class.prototype.constructor = Class;
【问题讨论】:
-
通常除了设置共享原型成员之外,您可能还想在子构造函数中重新使用父实例特定的构造函数代码:Animal.call(this).stackoverflow.com/questions/16063394/…
标签: javascript inheritance constructor prototype