继承构造逻辑,但在创建 Sub 对象时运行超级构造函数

Inherit construction logic, but run Super constructor on Sub object creation

本文关键字:对象 Sub 运行 构造函数 创建 继承      更新时间:2023-09-26

我用其他语言写过东西,你继承了一个类,当创建子类的对象时,超类构造函数被调用。 但是,在我发现从javascript继承到处都是的模式中,超级构造函数实际上是在建立继承时运行的。

例:

var thingy = function(){ this.constructionTime = new Date() };
var thing2 = function(){ this.type="thing2" };
thing2.prototype = new thingy();//thingy constructor actually runs here
var t2 = new thing2();//does NOT call thingy constructor
setTimeout(function(){
  var t3 = new thing2();
  t3.constructionTime == t2.constructionTime; // TRUE
},100);

然后我发现了一些不太常见的例子,他们做了这样的事情:

var athing = function(){
    this.constructionDate = new Date();
}
athing.prototype.showDate = function(){ console.log(this.constructionDate) };
var something = function(){
    athing.apply(this);
    this.note = "I'm something";
}
var x = new something();

然后调用 x = new something() 确实运行构造函数,但不继承方法。 所以我补充

something.prototype = athing.prototype;

它不给 x 方法,而是给新对象

y = new something();
y.showDate();//shows the date generated during its construction

确实有他们。

所以这是我可能过于宽泛的问题:我错过了什么吗? 除了希望您的超级构造函数只运行一次之外,是否有理由不使用此模式?

当你想要子类化时,请考虑使用

function Constructor() {
    SuperConstructor.apply(this);
    /* ... */
}
Constructor.prototype = Object.create(SuperConstructor.prototype);
Object.defineProperty(Constructor.prototype, 'constructor', {
    value: Constructor,
    configurable: true,
    writable: true
});
  • Constructor 中调用 SuperConstructor 会使Constructor实例具有在 SuperConstructor 内部设置的属性。
  • Constructor.prototype设置为 Object.create(SuperConstructor.prototype) 会使Constructor实例从 SuperConstructor.prototype 继承属性。
  • 由于Constructor.prototype已被替换,因此必须手动添加constructor属性。使用defineProperty以使其不可枚举。

Javascript是一种无类语言。 尝试将继承和超级构造函数等经典概念硬塞进去并不是一个好主意。