iT邦幫忙

第 12 屆 iThome 鐵人賽

DAY 27
0
自我挑戰組

草頭黃小姐的 30 天 JavaScript 自學小本本系列 第 27

Day 27 認識一下 ES6: class-base vs prototype-base

台灣生日快樂,今天就算是國慶日,文章也會持續進行:)

回到 JavaScript 上,物件導向有兩種寫法,分別為 class-base 和 prototype-base 兩種。

class-base 的寫法,會以 class 為開頭,定義 class,一層層寫下去,但是在 JavaScript,則是會用 prototype 來寫,還記得我們先前提到的,雞蛋糕的模型概念,用 new 就可以再一次壓出新一批的雞蛋糕,而以下是 JS 的 prototype 的物件導向概念:

function Pokemo(name,skill){
    this.name=name;
    this.skill=skill;
}

Pokemo.prototype.attack= function(){
    var sound= this.name.slice(0, 2).repeat(2);
    console.log("攻擊吧"+ this.name+ "!使出"+ this.skill + "「" + "」");
}

var Pikachu = new Pokemo("皮卡丘"+"十萬伏特");
Pikachu.attack();

以下寫法會印出:攻擊吧!皮卡丘!使出十萬伏特「皮卡皮卡」

但到了 ES6 的時候,則有 class 的寫法,並搭配用 constructor,這對很多寫其他程式語言的人來說好像比較有熟悉感,

class Pokemo{
 constructor(name, skill){
   this.name= name;
   this.skill= skill;
 }
}

var Pikachu = new Pokemo('皮','電');
console.log(Pikachu);

如果接下來,我想要加入功能,我就接著在 class 裡繼續寫:

class Pokemo{
 constructor(name, skill){
   this.name= name;
   this.skill= skill;
 }
 attack(){
   console.log('攻擊吧!')
 }
}

var Pikachu = new Pokemo('皮','電');
Pikachu.attack();

無論是 ES5 的 prototype 或是 ES6 用 class 來寫,他們其實都是物件導向,其實在背後的運作邏輯都是ㄧ樣的唷。


上一篇
Day 26 認識一下 ES6:物件的簡寫
下一篇
28 JavaScript 的基礎:AJAX 和 SetTimeout()
系列文
草頭黃小姐的 30 天 JavaScript 自學小本本30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言