constructor
1 2 3
| function Card(name) { this.name = name; }
|
1 2 3 4 5 6 7 8 9
| class Card { constructor(name) { this.name = name; }
showTitle() { console.log('title: ', this.name); } }
|
method
class
使用class的時候可以這樣宣告:
1 2 3 4 5 6 7 8 9
| class Card { constructor(name) { this.name = name; }
showTitle() { console.log('title: ', this.name); } }
|
如果我們希望method裡面的this每次使用一定都是用Card裡面的實體時,我們可以做綁定:
1 2 3 4 5 6 7 8 9 10
| class Card { constructor(name) { this.name = name; this.showTitle = this.showTitle.bind(this); }
showTitle() { console.log('title: ', this.name); } }
|
或是我們可以使用ES6+的arrow function:
1 2 3 4 5 6 7 8 9
| class Card { constructor(name) { this.name = name; }
showTitle = () => { console.log('title: ', this.name); } }
|
function
所以用function可以這樣寫嗎?:
1 2 3 4 5 6
| function Card(name) { this.name = name; this.showTitle = function() { console.log('title: ', this.name); } }
|
上面這樣寫是可以執行的,可是有一個問題是如果產生100個function就會有100個showTitle
要避免這種狀況,我們可以prototype的方式:
1 2 3 4 5 6 7
| function Card(name) { this.name = name; }
Card.prototype.showTitle = function() { console.log('title: ', this.name); }
|
繼承
使用上面的例子來示範繼承:
1 2 3 4 5 6 7 8 9
| class Card { constructor(name) { this.name = name; }
showTitle = () => { console.log('title: ', this.name); } }
|
計程之後可以使用parent的method使用
1 2 3 4 5 6 7 8 9
| class UserCard extends Card { constructor(name) { super(name); }
showUserTitle = () => { super.showTitle(); } }
|
也可以複寫parent的method
1 2 3 4 5 6 7 8 9
| class UserCard extends Card { constructor(name) { super(name); }
showTitle = () => { console.log('name: ', this.name); } }
|
比繼承更好的方法
之前我有寫一篇文章討論繼承優劣勢
這邊也簡單介紹一下更好的辦法實作你想要達到的目的