在 chapter4 已提過陣列與物件
本章的重點著重於於在 js 中物件導向(Object-oriented programming)的應用
_
作為開頭代表私有屬性
乍看有點抽象,舉生活中的例子來說:
方向盤、儀表板、油門、煞車 這些可被直接操控來駕駛的元素就是 interface
而 引擎、傳動系統、電路系統其運作原理與製造過程,這些背後的原理,即使不懂也不影響駕駛的部份就是 implementation,作為駕駛者並不需要直接與實作互動;只需要使用介面。
封裝的核心概念為,將『what(the interface)』 與『how(the implementation)』區分開來。
回到 javascript 的世界,所謂的 interface 表示物件與函式庫可使用的所有 public API,像是 .push(), .filter(), .map() 跟屬性值 (.length)
而實作的部分則是讓這些方法運行背後的實際程式碼跟演算法,像 .push() 的實作方法牽涉添加新元素與調整記憶體大小的複雜邏輯,無需了解工作原理即可有效的使用它
方法是用來儲存函式值的物件屬性,通常需要『幫呼叫它』的物件執行一些事情
當函式被當做方法呼叫,會被看成物件屬性並立即呼叫,用法為Object.method()
,而方法內的this則指向呼叫它的物件(The this keyword points to the Object that calls the method)
下方為建立物件與物件上方法的示例,以 Method Shorthand 語法呈現
let whiteRabbit = {
color:"white",
speak(line){console.log(`${this.color} rabbit says ${line}`)},
}};
whiteRabbit.speak("Oh, it's time to have lunch.");
另外這種較為傳統的作法 seperate function declaration 也通用,顧名思義就是將 function 於物件外宣告
但示例都會以 Method Shorthand 為主
function speak(line){
console.log(`${this.color} rabbit says ${line}`
}
let whiteRabbit = {
color:"white",
speak
};
whiteRabbit.speak("Oh, it's time to have lunch.");
另外,
切勿將arrow function 的寫法用於 Object method!
切勿將arrow function 的寫法用於 Object method!
切勿將arrow function 的寫法用於 Object method!
原因是因為 arrow function 本身沒有自己的 this context,當從物件呼叫由 arrow function 構成的方法時,它不會從呼叫它的物件上接收 this
let whiteRabbit = {
color:"white",
speak(line){console.log(`${this.color} rabbit says ${line}`)},
greet: (line)=> console.log(`${this.color} rabbit says ${line}`),
}};
whiteRabbit.speak("Oh, it's time to have lunch.");
whiteRabbit.greet("See you soon!"); // undefined rabbit says See you soon!
儘管方法跟屬性值都屬於物件,但它們仍有顯著差異
下方為方法與屬性的比較表格
name | value |
---|---|
method | function that performs an action or set of actions |
property | primitive values such as string, number or another object |