ES6:如何从实例访问静态 getter [英] ES6: How to access a static getter from an instance

查看:51
本文介绍了ES6:如何从实例访问静态 getter的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

How can i access a static getter from an instance of the class that implements that getter?

例如,我有这个类:

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

  constructor() {}
}

const c = new Component();

如何从组件"类的c"isComponent"调用?我四处阅读,我发现的都是这样的:

how can i call from "c" "isComponent" of "Component" class? I read around and all I found is something like that:

Object.getPrototypeOf(c).isComponent

但这不适用于我的情况,因为组件原型对象中没有isComponent"方法.如果我这样编写类,则上面的代码有效:

but this is not working on my case because there is no "isComponent" method in Component prototype object. The above code works if I write the class like this:

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

但这不是我想编写类的方式.我错过了什么?tnx

but this is not the way i would like to write classes. What am I missing? tnx

推荐答案

static 成为构造函数的属性,您可以通过 constructor 在实例上访问它属性:

statics become properties of the constructor function, which you can access on an instance via the constructor property:

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 语法,它会自动处理,因此人们忘记不再是问题.

Of course, that relies on constructor not having been mucked with. :-) Before the class syntax, you'd see people forgetting to set constructor properly in inheritance hierarchies all the time. Thankfully, with class syntax, it's handled automatically so people forgetting is no longer an issue.

理论上,实例可能有一个自己的"constructor 属性,隐藏原型上的那个.所以如果这是一个问题,你可以去原型:

In theory, the instance may have an "own" constructor property, shadowing the one on the prototype. So if that's a concern, you could go to the prototype:

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

或者,如果你知道它是什么构造函数,你可以直接去源码:

Alternatively, if you know what constructor it is, you can go direct to the source:

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 是您想要的构造函数.

...but only if you know in advance that Component is the constructor you want.

这篇关于ES6:如何从实例访问静态 getter的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆