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.
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.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With