--- tags: ES6, Javascript disqus: hackmd --- # [JS]類別(class) [Class 的基本语法](https://es6.ruanyifeng.com/#docs/class) [JavaScript ES6 class 關鍵字](https://www.fooish.com/javascript/ES6/class.html) [Classes - MDN](https://developer.mozilla.org/zh-TW/docs/Web/JavaScript/Reference/Classes) --- 在 ES6 中,引入了class(類別) 這個新的概念透過class這新的關鍵字,可以定義類別。 ```javascript= function Point(x, y) { this.x = x; this.y = y; } Point.prototype.toString = function () { return '(' + this.x + ', ' + this.y + ')'; }; var p = new Point(1, 2); p.toString(); //"(1, 2)" ``` 基本上,ES6 的class可以看作只是一個語法糖,它的絕大部分功能,ES5 都可以做到,新的class寫法只是讓對象原型的寫法更加清晰、更像面向對象編程的語法而已。上面的代碼用 ES6 的class改寫,就是下面這樣。 ```javascript= class Point { constructor(x, y) { this.x = x; this.y = y; } toString() { return '(' + this.x + ', ' + this.y + ')'; } } var p = new Point(1, 2); p.toString(); //"(1, 2)" ``` 上面代碼定義了一個“類”,可以看到裡面有一個constructor方法,這就是構造方法,而this關鍵字則代表實例對象。也就是說,ES5 的構造函數Point,對應 ES6 的Point類的構造方法。 --- `函數宣告(ES5)`和`類別宣告(ES6)`的一個重要差別在於函數宣告是hoisting(提升) ,類別宣告則不是。 你需要先宣告你的類別,然後存取它,否則像是下面的程式碼就會丟出一個 ReferenceError ```javascript= var p = new Polygon(); // undefined function Polygon() { } ``` ```javascript= var p = new Polygon(); // ReferenceError class Polygon {} ``` --- ### [constructor](https://hackmd.io/Yq5UUA5IRcigBgB_zUG3xQ?view)
×
Sign in
Email
Password
Forgot password
or
By clicking below, you agree to our
terms of service
.
Sign in via Facebook
Sign in via Twitter
Sign in via GitHub
Sign in via Dropbox
Sign in with Wallet
Wallet (
)
Connect another wallet
New to HackMD?
Sign up