本文實例講述了js定義類的方法。分享給大家供大家參考,具體如下:
以下是es5標準里定義類的方法:
<script>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);console.log(point);</script>
運行結果:
上面這樣用構造函數和原型混合的方法定義類,是為了每次new
新實例時可以共享方法,不用創建function
新實例。所以只有函數屬性放在原型對象里定義,其他屬性都在構造函數里定義。
es6里簡化了類的定義方法:
<script>class Point{ constructor(x,y){ this.x=x; this.y=y; } toString(){ return '('+this.x+', '+this.y+')'; }}let point=new Point(3,4);console.log(point);</script>
運行結果:
注意:類名首字母要大寫
(另:原文代碼中class Point(x,y)
定義會導致運行錯誤,本文予以修正。)
希望本文所述對大家JavaScript程序設計有所幫助。
新聞熱點
疑難解答