gpt4 book ai didi

javascript - 从 "abstract"base "class"调用构造函数

转载 作者:行者123 更新时间:2023-11-29 21:52:25 25 4
gpt4 key购买 nike

我有以下要求:

  • 我的“ super ”“类”必须是“抽象的”
  • 我的“ super ”“类”的构造函数必须由继承类调用
  • 继承“类”的构造函数必须做一些事情......

我是这样试过的:

var Father = function() {
if(this.constructor === Father) {
// ...I throw an exception here to make it "abstract"...
}
alert('Father constructor');
};
Father.prototype.say = function() {
alert('Im your father');
};

var Son = function() {
Father.call(this);
alert('Son constructor');
};
Son.prototype = Object.create(Father.prototype);

var son = new Son();
son.say();

使用 this.constructor === Father 我尝试将 Father 实现为“抽象”“类”(如果是这样,我将在我的代码中抛出一个错误真实代码)。

Father.call(this); 确保调用父类(super class)的构造函数。但是 this.constructor === Father 是真的。

有没有更好的方法?

最佳答案

问题是您在进行推导时没有正确设置 constructor 属性。在这一行之后:

Son.prototype = Object.create(Father.prototype);

你需要

Son.prototype.constructor = Son;

这只是使用构造函数进行这种继承的样板文件的一部分。如果没有它,Son.prototype 将继承 Father.prototype.constructor 属性,该属性由 JavaScript 引擎在创建 Father 函数时设置。您必须为 Son 显式执行此操作,因为您要替换 Son.prototype 上的对象(这是正确的做法,您然后只需要执行此 constructor 修复)。

关于javascript - 从 "abstract"base "class"调用构造函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28410158/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com