Let's say I have a class that looks like this
class Foo {
bar() {
console.log('bar');
}
baz() {
console.log('baz');
}
// other methods...
}
and I want all of its methods to be unconditionally called whenever a new instance is created. How would I go about that?
I'm currently doing it by calling each method in the class constructor method
class Foo {
constructor() {
this.bar();
this.baz();
// other methods
}
bar() {
console.log('bar');
}
baz() {
console.log('baz');
}
// other methods...
}
here's a snippet of that
class Foo {
constructor() {
this.bar();
this.baz();
// other methods
}
bar() {
console.log('bar');
}
baz() {
console.log('baz');
}
// other methods...
}
new Foo();
Is there a better way to do this?
This seems to be the closest to what I want to achieve. It works by ditching class methods and using IIFEs in classProperties instead.
So something like this
class Foo {
bar = (() => {
console.log('bar');
})()
baz = (() => {
console.log('baz');
})()
}
new Foo();
and it works well on Chrome but the majority of other browsers don't yet have support for classProperties since they were added in ES9
My question is:
If I have a class with a number of methods in it, can I call all of them whenever a new instance of that class is created without having to call each individual method in the constructor method of that class?
In the context of this question, you can completely ignore the need to pass parameters to the methods. I don't need to pass any parameters to any of the class methods.