Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Default method on a class

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
like image 624
Rog Avatar asked Sep 10 '25 22:09

Rog


1 Answers

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
like image 135
dimlucas Avatar answered Sep 13 '25 11:09

dimlucas