iT邦幫忙

2025 iThome 鐵人賽

DAY 13
0
佛心分享-讓我升級的那些書

溫故而知新:Eloquent Javascript 閱讀筆記系列 第 13

Chapter 6 物件的秘密(call,bind,apply/prototype/class)-day13

  • 分享至 

  • xImage
  •  

call, bind, apply

昨天提到呼叫 object 上的 method 時,this 會指到 object 本身
但如果要直接 pass this as parameter,可使用 call method

call 用於在呼叫函式時傳入指定的 this 參數
用法如下
method.call(thisArg, arg1, ..., argN)

另外 call, bind, apply 這三個語法有相關
以下為比較表格

name 作用 用法
call 在呼叫函式時傳入thisArg,函式會馬上執行 method.call(thisArg, arg1, ... , argN)
bind 綁定thisArg,函式不會馬上執行 bind(thisArg)
apply 跟call類似,但傳入的參數為array-like object method.apply(thisArg, [arg1 , .. ,argN ])

原型 prototype

可用 Object.getPrototypeOf(obj) 取得物件或各種變數的 prototype
使用Object.create()則可以建立具有特定原型的物件

以下為 Object.create() 建立具特定原型物件的示例:

let protoRabbit = {
    ear:2,
    leg:4,
    speak(line){console.log(`The ${this.type} rabbit says '${line}'`));
    }
}

let whiteRabbit = Object.create(protoRabbit);
whiteRabbit.type = "white";
whiteRabbit.speak("Nice weather!"); // The white rabbit says 'Nice weather!'

另外 js 在處理 primitive value (string, number, boolean)時,實際上會把 primitive value 包在 wrapper object 中

name prototype
object Object.prototype
function Function.prototype
array Array.prototype
string String.prototype
number Number.prototype

這些不同種類的原型有其對應的方法,諸如 string prototype 有 string.toUppercase()

prototype of undefined & null?

另外,undefinednull沒有屬於它們的屬性也沒有原型
當然也 沒有任何 prototype method 可用
若嘗試用 Object.getPrototypeOf() 去取得原型值,會得到無法將 undefined 及 null 轉變為物件的錯誤

Object.getPrototypeOf(undefined); // Uncaught TypeError: Cannot convert undefined or null to object

類別與實體 class & instance

類別(class)定義物件的方法和屬性,在類別內,定義物件實體應具有的屬性與方法的部分則稱為建構子(constructor)
由類別所產生的物件稱之為實體(An instance is the actual object created from the class)

舉例來說
有一本餅乾食譜教導如何製作不同的餅乾,這本餅乾食譜代表餅乾這個類(class),描述每種不同餅乾材料跟對應製作方法的內容則為建構子(constructor),而最終被製作出來的餅乾成品就是實體(instance),每個不同的餅乾都是獨立的物件實體

建構子必定為類的一部份
The constructor is always a part of class (in the class).

以下為宣告類別的示例:

class CookieRecipe{
    constructor(type,ingredient){
        this.type = type;
        this.ingredient = ingredient;
    }
    bake(time, temperature){
        console.log(`The ${this.type} cookies need to bake at ${temperature} degrees for ${time} minutes.`);
    }
}

let chocoCookie = new CookieRecipe("choco", {
    sugar: 1,
    butter: 1,
    flour: 3,
});
chocoCookie.bake("10-15", 190);

上一篇
Chapter 6 物件的秘密(interface/implementation/method)-day12
下一篇
Chapter 6 物件的秘密(Map/Associative Array)-day14
系列文
溫故而知新:Eloquent Javascript 閱讀筆記16
圖片
  熱門推薦
圖片
{{ item.channelVendor }} | {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言