以下是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+')'; } }
注意:類名首字母要大寫