Function.prototype.call 在 class 上进行动态继承

Function.prototype.call on class to make dynamic inheritance

你好,

我正在尝试使用 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'
  }
}

第一次尝试没有成功,因为 class 不是函数,只有函数的原型中有 call 方法。 第二次尝试没有报错,只是没有继承Person.

中设置的测试值

如果我将 Person class 更改为:

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

但不幸的是,我没有足够的钱来更改我试图像这样继承的 class' 代码。

我在网上搜索了很多,但找不到为什么 call 函数对基于 class 的 classes 不起作用。这让我感到困惑,因为您可以轻松地将基于 class 的 classes 重写为基于 function 的 classes.

有没有人知道如何使用 prototype.call 方法继承 class?

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

尽管 class 对象是函数并且 do 继承了 call 方法,尝试使用 className.call(...) 将产生类似于

TypeError: class constructors must be invoked with 'new'

第一个答案:由于上述原因,您将不能使用“Function.prototype.call”调用class的构造函数。


如评论中所述,扩展基 class 是创建构造函数的替代方法,但是当写成 class 声明时 不提供动态继承。

然而,这并不妨碍您动态扩展写在工厂函数中的 class 表达式。例如:

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)