传统的使用function定义类:
function Person(name,age){ this.name=name; this.age=age; } Person.prototype.addAge=function(){ this.age++; }; Person.prototype.setName=function(name){ this.name=name; }
而使用class的方式代码会更加简洁易懂,并且使用class还可以很方便的实现继承、静态的成员函数,而不需要再自己去通过一些方法实现,代码如下:
class Person(name,age){ constructor(name,age){ this.name=name; this.age=age; } addAge(){ this.age++; } setName(name){ this.name=name; } }