您可以更改 ES6 class 定义以附加新的实例方法吗?

Can you alter an ES6 class definition to attach new instance methods?

有没有办法追溯(即在 class 已经定义之后)向 ES6 class 添加实例方法?

考虑以下 class:

class Thing {}

我现在想将 hello 方法附加到 Thing,然后可以在其实例上调用该方法,如下所示:

let thing = new Thing();
thing.hello();

可能吗?

(当然,我可以做一个子class,但这不是我在这里要问的。)

只需使用 ES5 中的 prototype

class Thing {
  hello () {
    console.log('Hey!');
  }
}

var t = new Thing();

t.hello(); // Hey!

Thing.prototype.goodbye = function () {
  console.log('Bye!');
}

t.goodbye(); // Bye!

或者您可以使用 Object.assign

Object.assign(Thing.prototype, {
    hello(arg1, arg2) {
        // magic goes here
    }
});

这相当于

Thing.prototype.hello = function (arg1, arg2) {
    // magic goes here
};