Function.prototype.call调用类以进行动态继承



你好,

我正在尝试使用function.prototype.call来确保动态继承。

以下是我尝试做的一个基本示例:

class Person {
constructor(name, test) {
this.name = name;
this.test = test;
}
}
class Police {
constructor(name, badge, ...manyArgs) {
//Attempt 1:
Person.call(this, name, 'hello world');
//I also tried:
Person.constructor.call(this, name, 'hello world');
console.log(this.test); //This should print a log message of 'hello world'
}
}

第一次尝试不起作用,因为类不是函数,只有函数的原型中有调用方法。第二次尝试没有给出错误,只是没有继承Person中设置的测试值。

如果我将Person类更改为:

function Person(name, test) {
this.name = name;
this.test = test;
}

但不幸的是,我没有像这样奢侈地更改我试图继承的类代码。

我在网上搜索了很多,但找不到为什么call函数不适用于基于class的类。这让我很困惑,因为您可以很容易地将基于class的类重写为基于function的类。

有人知道如何使用prototype.call方法来继承类吗?

JavaScript中的类构造函数只能使用类扩展中的newReflect.constructsuper调用。这收紧并标准化了使用普通function对象的替代构建技术。

尽管class对象是函数,并且确实继承了call方法,但尝试使用className.call(...)会产生类似的错误

TypeError:类构造函数必须使用"new"调用

第一个答案:由于以上原因,您将无法使用"Function.protype.call"调用类的构造函数。


如注释中所述,扩展基类是创建构造函数的一种替代方法,但当作为类声明编写时,不提供动态继承。

然而,这并不能阻止您动态扩展在工厂函数中编写的类表达式。例如:

class Person {
constructor(name, test) {
this.name = name;
this.test = test;
}
}
// factory function:
function policeExtend(baseClass) {
return class Police extends baseClass {
constructor(name, badge) {
super(name, "'just testing'");
this.badge = badge;
}
};
}
const PolicePerson = policeExtend(Person);
let officer = new PolicePerson("chief", 100);
console.log( officer.name, officer.badge, officer.test)

最新更新