0

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';
    }
  }
ZEE
  • 2,931
  • 5
  • 35
  • 47
  • 1
    This is what might be coming next: https://gist.github.com/jeffmo/054df782c05639da2adb – Felix Kling May 26 '15 at 22:07
  • Yes... that seems to be the way to go... hope it will become a reality soon... yet some features still missing... – ZEE May 27 '15 at 18:32

2 Answers2

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

just-boris
  • 9,468
  • 5
  • 48
  • 84
  • fine... but what is intersting in this evolution is to grab the best practices os OOP... like logic syntax... encapsulation... Maybe in the future generics, operator overloading, etc. – ZEE May 27 '15 at 00:58
  • 1
    You can use experimental babel feature - [es7.classProperties](https://gist.github.com/jeffmo/054df782c05639da2adb). Here is [modified version of example](http://babeljs.io/repl/#?experimental=true&evaluate=true&loose=false&spec=false&code=class%20Foo%20%7B%0A%20%20%0A%20%20baz%20%3D%20'baz'%3B%0A%20%20%0A%20%20constructor()%20%7B%0A%20%20%20%20%0A%20%20%7D%0A%20%20%0A%20%20static%20bar%20%3D%20'bar'%3B%0A%7D%0A%0Aconsole.log(Foo.bar)%0Aconsole.log(new%20Foo().baz)). But be aware, it will not be implemented natively soon – just-boris May 27 '15 at 07:04
1

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.

Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143