There is a way in JS to execute a default method when I call a instance?
Example: Let's assume I have the following class named MyClass
, then I start a instance of this class named foo
, I want that when I call foo
execute the default
method of MyClass
.
class MyClass {
constructor () {
this.props = {
question: 'live, universe, everything',
answer: 42
}
}
default () {
return this.props
}
hello () {
return 'hello world'
}
}
const foo = new MyClass()
// execute the default method
console.log(foo) // log: {question: 'live, universe, everything', answer: 42}
// execute hello method
console.log(foo.hello()) // log: hello world
The only default method that is called when instantiating an object is the constructor
.
In ES6 you can return whatever you want from the constructor so the following code is valid:
class MyClass {
constructor () {
var instance = {
question: 'live, universe, everything',
answer: 42,
hello: () => { return 'hello world' }
}
return instance;
}
}
You can then instantiate an object like this:
var foo = new MyClass();
foo.hello(); //Hello world
console.log(foo.question); //live, universe, everything
console.log(foo.answer); //42
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