js定义类

以下是es5标准里定义类的方法:

function Point(x,y){
    this.x=x;
    this.y=y;
}
Point.prototype.toString=function(){
    return '('+this.x+', '+this.y+')';            
}
var point=new Point(1,2);

上面这样用构造函数和原型混合的方法定义类,是为了每次new新实例时可以共享方法,不用创建function新实例。所以只有函数属性放在原型对象里定义,其他属性都在构造函数里定义。

es6里简化了类的定义方法:

class Point(x,y){
      constructor(x,y){
        this.x=x;
        this.y=y;
       }
       toString(){
          return '('+this.x+', '+this.y+')';  
       }
}

 注意:类名首字母要大写

原文地址:https://www.cnblogs.com/wxcbg/p/8610945.html