【问题标题】:ES6: How to access a static getter from an instanceES6:如何从实例访问静态 getter
【发布时间】:2017-05-16 13:12:44
【问题描述】:

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

例如,我有这个类:

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

  constructor() {}
}

const c = new Component();

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

Object.getPrototypeOf(c).isComponent

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

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

但这不是我想写课程的方式。我错过了什么? tnx

【问题讨论】:

标签: javascript class static ecmascript-6 getter


【解决方案1】:

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

X = Component.isComponent

所以不要在实例上调用它,而是在类本身上调用它。这听起来合乎逻辑,因为静态变量没有 this 变量。静态值对于您的类的所有实例都相同。

【讨论】:

    【解决方案2】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-02-02
      • 1970-01-01
      • 2013-10-28
      • 2016-03-17
      • 2016-02-25
      • 2023-03-07
      • 1970-01-01
      • 2019-07-13
      相关资源
      最近更新 更多