ES6 classes, member properties definitions as static/shared

一曲冷凌霜 提交于 2019-12-08 09:18:30

问题


I am testing classes in ES 6 with io.js 2.xx the example below I took from Mozilla, Things are getting on tracks (OOp in JS), at least we now have direct inheritance (at syntax level) with the 'extends' directive... the problem I pose is that member properties are defined inside constructor this is at least a syntax problem... (been searched through the web and found very few information about this) will be more a of a problem when ESxx try to had visibility directives to property members (in a near future I guess)

Anyway, for now... How do I declare a shared/static property?

// example from Mozilla
class Polygon 
  {
  constructor(height, width) 
    {
    this.name = 'Polygon';
    this.height = height;
    this.width = width;
    }
  }

class Square extends Polygon 
  {
  constructor(length) 
    {
    super(length, length);
    this.name = 'Square';
    }
  }

回答1:


You can still just use old syntax to add properties to constructor function (static properties) or prototype (predefined instance properties)

class Foo {
  constructor() {

  }
}
Foo.bar = 'bar';
Foo.prototype.baz = 'baz';

console.log(Foo.bar) // 'bar'
console.log(new Foo().baz) // 'baz'

And it will work. Look at example on babel-repl




回答2:


You can define static or prototype properties with getters:

class Foo {
  static get bar() {
    return 42;
  }

  get bar() {
    return 21;
  }
}

It's not ideal, but it works.



来源:https://stackoverflow.com/questions/30469550/es6-classes-member-properties-definitions-as-static-shared

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!