iT邦幫忙

3

JS 原型鏈

JS 原型鏈

若要建立兩個汽車的實體,該如何建立?

Why use OO

  • 減少重複的程式碼
  • 減少記憶體的使用
  • 使實體有關聯性

類別、物件

  • 類別: 為實體的藍圖、範本 Ex:車子設計圖
  • 物件: 透過類別建立出來的實體(instance) Ex:車子

原型鏈特性

  • JS prototype Base 繼承方式
  • 最上層的原型為物件
  • 向上尋找屬性、方法的特性
  • 繼承特性 (不同實體,繼承同一屬性、方法)
  • 類別使用 new關鍵字 建造出實體

小建議

  • 類別 使用大寫作為開頭 Car
  • 靜態方法 使用_作為開頭 static _add()
  • 使用 Object.getPrototypeOf(obj) 取得原型
  • 使用 ES6 Class
  • 使用 預設參數 & 解構

Level 0 (直接建立物件)

  • 直接建立兩個物件
  • 其缺點: 繁瑣、無法統一管理、擴展性差、占用記憶體
  const carA = {
    wheels: 4,
    pressHorn() { console.log('AAA') },
  }
  const carB = {
    wheels: 4,
    pressHorn() { console.log('BBB') },
  }

Level 1 (prototype建立藍圖)

  • 利用 JS prototype 建立藍圖
  • 使用 new 關鍵字建立實體
  • 缺點: function功能相同,但每次創造實體時都複製一份,占用了不必要的記憶體
  // ES6 default parameter
  const Car = function (brand, sound = '888') {
    // ES5 預設變數寫法
    this.brand = brand !== undefined ? name : 'toyota'
    this.wheels = 4
    this.pressHorn = function () { console.log(sound) }

    // 勿使用此做預設變數,遇到 falsy 會出錯
    this.test1 = test !! undefined ? test : '123'
    this.test2 = test || '123'
  }
  const carA = new Car('AAA')
  const carB = new Car('BBB', 'BBB')

Level 2 (在原型上建立共用方法)

  • 將 Function 掛載到藍圖的 prototype
  • 利用原型鏈 向上尋找的特性,實體無該屬性、方法即往上尋找可用的屬性、方法
  • 寫於原型僅佔一份記憶體
  Car.prototype.pressHorn = function () {
    console.log(`${this.brand} ${this.sound}`)
  }
  // true 表 Function 來自同一個記憶體位置
  console.log(carA).pressHorn() === carB.pressHorn())

Level 3 (ES5 Reveal Pattern)

  • 封裝內部資料,公開想公開的介面
  • ES5 範例
  const Car = function (brand,sound) {
    this.brand = brand
    this.wheel = 4
    return {
      brand,
    }
  }
  const test = new Car('A','AAA')
  console.log(test.wheels) // undefined 不可取得
  console.log(test.brand) // 可取得

Level 4 (ES6 Class)

  • JS 為 prototype base,因此 Class 僅為 prototype的語法糖
  • 使用 Class 使語法更精簡
  class Car {
    // 寫於 constructor的內容,皆會在記憶體創一份新的
    // 因此 方法避免寫於 constructor 內部
    constructor(brand = 'default') {
      // constructor內容會於實體建立時執行
      this.brand = brand
      this.init() 
    }
    init() { console.log('init') }
    pressHorn(){
      console.log(`${this.brand} ${this.sound}`)
    }
  }

Bonus: 預設參數 & 解構

  const User = function ({ name = 'default', age }) {
    this.name = name // 可預設但可傳入修改
    this.age = age
    this.gender = 'male' // 可預設不給用傳入的
  }
  // 傳入順序無差,以 Key為基準
  let test = new User({ age: 30 })
  console.log(test.name, test.gender) // 'default' 'male'

取得原型語法

  • 取得原型1: 雙下底線proto (不推薦使用 效能差)
  • 取得原型2: Object.getPrototypeOf(obj) (建議使用、IE9+)
// ESLint/MDN 不建議使用 __proto__ 取得原型
const CarProto = Car.__proto__
// 推薦使用 ES5
const CarProto = Object.getPrototypeOf(Car)

instanceof 原理 (判斷是否有該原型)

  • 判斷目標是否在其原型鏈之下
  // 判斷 'str' 是否在 String 之下
  console.log('str' instanceof String) 
  // false,因為此種表示方法為原始型別,其原型鏈為 undefined

  // 使用 new 關鍵字建立物件
  const newStr = new String('newStr')
  console.log(newStr instanceof String )
  console.log(newStr instanceof Object )
  // 皆true,String & Object 皆於 newStr 原型鏈上

參考資料

保哥 物件導向基礎
偷米 ES6 Class介紹


圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言