Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript ES6 shared class variable

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.

like image 407
Sean Lynch Avatar asked Apr 28 '16 17:04

Sean Lynch


People also ask

Can JavaScript classes have variables?

We can also define private variables in a class. Private variables must be explicitly declared inside the class body and are prefixed by a #. They can only be accessed inside class member functions.

How do you declare a variable in a class in JavaScript?

To declare a variable within a class, it needs to be a property of the class or, as you did so, scoped within a method in the class. It's all about scoping and variables are not supported in the scope definition of a class.

Does JavaScript support class like inheritance?

JavaScript is a bit confusing for developers experienced in class-based languages (like Java or C++), as it is dynamic and does not have static types. When it comes to inheritance, JavaScript only has one construct: objects. Each object has a private property which holds a link to another object called its prototype.

How can we declare a variable which can't be updated in ES6?

Unlike variables declared using let keyword, constants are immutable. This means its value cannot be changed. For example, if we try to change value of the constant variable, an error will be displayed.


1 Answers

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.

like image 53
Bergi Avatar answered Sep 20 '22 16:09

Bergi