【问题标题】:Can you alter an ES6 class definition to attach new instance methods?你能改变一个 ES6 的类定义来附加新的实例方法吗?
【发布时间】:2015-08-13 23:53:24
【问题描述】:

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

考虑以下类:

class Thing {}

我现在想将hello 方法附加到Thing,然后可以像这样在其实例上调用:

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

有可能吗?

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

【问题讨论】:

  • 原型继承的工作方式与 ES5 中的相同。只需添加另一个属性。添加一个 method (在 ES6 意义上),使其工作方式与在类文字中声明的一样是 a bit more complicated

标签: javascript class methods ecmascript-6


【解决方案1】:

就像在 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!

【讨论】:

    【解决方案2】:

    或者你可以使用 Object.assign

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

    这相当于

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

    【讨论】:

    • 不完全等效 - 您正在使用方法声明。哦,super 将不起作用。
    • @Bergi:啊。现在明白了。谢谢你让我知道:)
    猜你喜欢
    • 1970-01-01
    • 2023-04-11
    • 2013-11-10
    • 1970-01-01
    • 2015-12-18
    • 1970-01-01
    • 2016-01-16
    • 2010-11-02
    • 1970-01-01
    相关资源
    最近更新 更多