7

I have a class that looks like this:

class Foo {
    constructor(arg1, arg2) {
        // ...

        this._some_obj = new SomeObj({
            param1: arg1,
            param2: arg2
        });
    }

    // ...
}

module.exports = Foo;

Now I want to do the same thing but with _some_obj shared between all instances of the class.

After searching around I'm unclear as to the correct way to do this in ES6.

Sean Lynch
  • 2,852
  • 4
  • 32
  • 46
  • well.. how would you do it in es5? – Kevin B Apr 28 '16 at 18:02
  • If it's shared between all instances, what is the expected behavior for the arguments? Would the first call initialize it with whatever the first args happen to be? – loganfsmyth Apr 28 '16 at 19:06
  • @loganfsmyth - Yes I hadn't really thought this through in that regard. I assume there should be some type of initialization function instead of putting those args in the constructor. – Sean Lynch Apr 28 '16 at 19:21

2 Answers2

7

As known from ES5, you can just put it on the class's prototype object:

export class Foo {
    constructor(arg1, arg2) {
        …
    }
    …
}
Foo.prototype._some_obj = new SomeObj({
    param1: val1,
    param2: val2
});

Or directly on Foo, if you don't need to access it as a property on instances.

Bergi
  • 630,263
  • 148
  • 957
  • 1,375
  • I read that defining properties on the prototype is a bad idea and that this is why it wasn't included in ES6 classes in the first place. Is that not true? – Sean Lynch Apr 28 '16 at 18:11
  • @SeanLynch it's not a good diea to REdefine prototype properties on classes you didn't make. For instance, `Math.prototype.min = ` is not a good property to overwrite, because it effects every instance of `Math.min` – Sterling Archer Apr 28 '16 at 18:13
  • @SterlingArcher - I see. I didn't really understand that. Thank you! – Sean Lynch Apr 28 '16 at 18:15
  • adding to classes you own isn't the same as adding to native objects prototypes (which can seriously mess with any libraries you may use) – rlemon Apr 28 '16 at 18:15
  • In this case, how would I get the values of `arg1` and `arg2` to be available to the constructor of SomeObj. I think `Foo.prototype._some_obj` would be created before the constructor is ever called. – Sean Lynch Apr 28 '16 at 18:19
  • @SeanLynch: Yes, it's not a good idea to put mutable objects on the prototype, like [e.g. given arrays](http://stackoverflow.com/q/4425318/1048572). But it's exactly what the question asked for: to be shared. If that is what you need, then it's fine. – Bergi Apr 28 '16 at 18:40
2

Use static to have class properties.

class MyClass {
  static myStaticProp = 42;

  constructor() {
    console.log(MyClass.myStaticProp); // Prints '42'
  }
}

N.B: this is a feature already implemented in Babel, but is still experimental as only at the 1st proposal stage.

Thomas Ruiz
  • 3,611
  • 2
  • 20
  • 33