【发布时间】:2018-02-01 15:11:18
【问题描述】:
我们如何在 ES6 中使用 class 关键字来像在 ES5 中那样动态添加方法?
https://jsfiddle.net/user1212/7c57eou3/
class Person{
constructor(name){
this.name = name;
}
getName(){
return this.name;
}
setName(name){
this.name = name;
}
}
function Company(cName){
this.cName = cName;
}
Company.prototype.getName = function(){
return this.cName;
}
Person 类定义后如何添加新方法?
【问题讨论】:
-
在完全中与 ES5 中的方式相同。
-
就像@Bergi 说的一样,这是因为Javascript中的类不是新类型,只是普通功能原型的装饰器。
-
事后向原型添加方法的用例是什么?当您不能在类定义时添加方法时,我想不出任何理由自己这样做。
-
@jfriend00 添加用户定义的jQuery方法就是一个例子。
-
@Barmar 但是 jQuery 的集合不使用
class语法,是吗?
标签: javascript inheritance ecmascript-6