使用es6的class和使用function的prototype两种方法定义类的区别

传统的使用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;
  }
}



猜你喜欢

转载自blog.csdn.net/qq_34928693/article/details/80118562