类的默认方法

Rog*_*Rog 1 javascript node.js ecmascript-6

在调用实例时,JS有一种方法可以执行默认方法吗?

示例:假设我有以下类命名MyClass,然后我启动这个类的实例命名foo,我希望当我调用fooexecute default方法时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
Run Code Online (Sandbox Code Playgroud)

dim*_*cas 5

实例化对象时调用的唯一默认方法是constructor.

在ES6中,您可以从构造函数返回任何内容,因此以下代码有效:

    class MyClass {
        constructor () {
              var instance = {
                    question: 'live, universe, everything',
                    answer: 42,
                    hello: () => {  return 'hello world' }
              }
              return instance;
        }
     }
Run Code Online (Sandbox Code Playgroud)

然后,您可以实例化一个这样的对象:

var foo = new MyClass();
foo.hello(); //Hello world
console.log(foo.question);    //live, universe, everything
console.log(foo.answer);    //42
Run Code Online (Sandbox Code Playgroud)