昨天提到呼叫 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 ]) |
可用 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()
另外,undefined
跟 null
既沒有屬於它們的屬性也沒有原型
當然也 沒有任何 prototype method 可用
若嘗試用 Object.getPrototypeOf()
去取得原型值,會得到無法將 undefined 及 null 轉變為物件的錯誤
Object.getPrototypeOf(undefined); // Uncaught TypeError: Cannot convert undefined or null to object
類別(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);