ES6:如何从实例访问静态 getter

ES6: How to access a static getter from an instance

如何从实现 getter 的 class 实例访问静态 getter?

例如,我有这个 class:

class Component {
  static get isComponent() { return true; }

  constructor() {}
}

const c = new Component();

如何从 "c" "isComponent" 或 "Component" class 呼叫? 我四处阅读,发现的都是这样的:

Object.getPrototypeOf(c).isComponent

但这不适用于我的情况,因为组件原型对象中没有 "isComponent" 方法。如果我这样写 class,上面的代码就可以工作:

Component.prototype.isComponent = () => { return true; }

但这不是我想写 classes 的方式。我错过了什么?发送

statics 成为构造函数的属性,您可以通过 constructor 属性:

在实例上访问它
console.log(c.constructor.isComponent);

class Component {
  static get isComponent() { return true; }

  constructor() {}
}

const c = new Component();
console.log(c.constructor.isComponent); // true

当然,这取决于 constructor 没有被弄脏。 :-) 在 class 语法之前,您会看到人们总是忘记在继承层次结构中正确设置 constructor。值得庆幸的是,使用 class 语法,它会自动处理,因此人们忘记不再是问题。

理论上,实例可能有一个“自己的”constructor 属性,遮蔽原型上的那个。所以如果这是一个问题,你可以去原型:

console.log(Object.getPrototypeOf(c).constructor.isComponent);

class Component {
  static get isComponent() { return true; }

  constructor() {}
}

const c = new Component();
console.log(Object.getPrototypeOf(c).constructor.isComponent); // true


或者,如果您知道它是什么构造函数,您可以直接访问源代码:

console.log(Component.isComponent);

class Component {
  static get isComponent() { return true; }

  constructor() {}
}

// const c = new Component(); <== Don't need it
console.log(Component.isComponent); // true

...但前提是您事先知道 Component 是您想要的构造函数。

你问的问题是错误的。您想要 Class 的实例中的 getter,但这不是静态的工作原理。 I static 是在 Class 本身上声明和初始化的,所以如果你想获得它的值,你应该这样做:

X = Component.isComponent

所以不要在实例上调用它,而是在 class 本身上调用它。这听起来合乎逻辑,因为 static 没有 this 变量。 static 的值对于 class.

的所有实例都是相同的