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

查看:107
本文介绍了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();

如何从组件类的cisComponent调用?
我读过,所有我发现的都是这样的:

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

但这不适用于我的情况,因为Component原型对象中没有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 s成为构造函数的属性,你就是可以通过构造函数属性访问实例:

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

当然,这取决于构造函数没有被破坏。 :-)在 class 语法之前,你会看到人们忘记在继承层次结构中正确设置构造函数 。值得庆幸的是,使用 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.

当然,实例可能有一个自己的构造函数属性,遮蔽原型上的那个属性。因此,如果这是一个问题,你可以去原型:

Of course, 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

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

Of course, 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 of course, only if you know in advance that Component is the constructor you want.

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

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