【问题标题】:Is there a way to reference "the current class" from a Javascript class method有没有办法从 Javascript 类方法中引用“当前类”
【发布时间】:2022-01-06 05:29:07
【问题描述】:

我想知道是否有一种方法可以在 Javascript 类中引用“当前类”而不是按名称的类。

例如:

class MyBase{
    static makeNew(id){
        const newInstance = new --currentClass--;// magic happens here
        newInstance.id = id;
        return newInstance;
    }
}

class A extends MyBase{}
class B extends MyBase{}

const newA = A.makeNew(1);
const newB = B.makeNew(379);

有没有办法让我编写MyBase::makeNew,这样当它从A 类调用时,它返回一个A 的新实例,但是当从B 类调用时,它返回B的新实例?

【问题讨论】:

  • 你试图让你的类的构造函数成为一个虚函数,这在定义上是不可能的(即,根据 OOP 的原则)。
  • 这些类都没有构造函数。对于我想做的事情,如果需要,它们可以各自定义自己的构造函数。

标签: javascript oop


【解决方案1】:

由于调用签名是这样的:

A.makeNew(1);
B.makeNew(379);

这可能看起来很熟悉 - 您可以使用 this 来引用它被调用的对象。

class MyBase{
    static makeNew(id){
        const newInstance = new this();
        newInstance.id = id;
        return newInstance;
    }
}

class A extends MyBase{}
class B extends MyBase{}

const newA = A.makeNew(1);
const newB = B.makeNew(379);

console.log(newA instanceof A);
console.log(newB instanceof B);

【讨论】:

  • 非常好 - 谢谢。我认为这很简单,但我不会是第一个不确定this 在给定上下文中究竟是什么意思的程序员。再次感谢。
猜你喜欢
  • 2011-11-13
  • 2011-05-20
  • 1970-01-01
  • 2019-12-12
  • 2021-06-19
  • 1970-01-01
  • 2015-02-20
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多