JavaScript 裡有一個初學者常忽略的關鍵事實:函式也是值。方法和屬性在語言層面並沒有差別,都只是一個可以賦值、傳遞、呼叫的參照。理解了這點,很多看似神奇的寫法就會變得很自然。
<script>
var test = new Object();
test["a"] = 1;
test["b"] = "string";
test["c"] = false;
alert(test["a"]); // 顯示 1
</script>
物件本質上就是「key → value」的對照表。用中括號搭配字串 key 賦值,等同於用點語法:
test.a = 1; // 與 test["a"] = 1 完全等價
test['a'] = 1; // 同樣等價
差別在於何時決定 key:點語法的名稱寫死在程式碼裡,中括號可以放變數,讓 key 在執行階段才決定:
var key = 'a';
console.log(test[key]); // 1
console.log(test.key); // undefined,因為沒有名為 "key" 的屬性
這個特性在動態遍歷、組裝資料時非常有用。
<script>
var test = {
a: 1,
b: "string",
c: false,
d: function show(){ alert("OK"); }
};
var show = test.d; // 把 d 賦值給 show
show(); // 顯示 OK
</script>
這段程式說明了重點:d 這個屬性的值恰好是一個函式,所以我們可以把它取出來另外賦值給 show,然後直接呼叫 show()。這就是所謂的「方法」——它並不是什麼特殊語法,只是「值為函式的屬性」。
也因為如此,函式可以像其他值一樣被四處傳遞:
var obj = {
count: 0,
increment: function(){ this.count++; return this; },
reset: function(){ this.count = 0; return this; }
};
obj.increment().increment().reset(); // 方法回傳 this 就能串接呼叫
console.log(obj.count); // 0
// 當回呼傳遞
[1, 2, 3].map(obj.increment); // this 會出問題,見下
// 當資料存放
var registry = { handler: obj.increment };
registry.handler.call(obj);
「函式是值」帶來一個重要副作用:函式被取離物件後,就失去了 this。
var show = test.d;
show(); // 若 show 內部用 this,this 會是 window 或 undefined
test.d(); // 這樣呼叫,this 才會是 test
規則是:this 由呼叫方式決定,而非定義位置。用 obj.method() 呼叫,this 是 obj;用 var f = obj.method; f() 呼叫,this 就變成全域物件(strict mode 下是 undefined)。
解法有三種:
// 1. call / apply 明確指定
var f = obj.increment;
f.call(obj);
// 2. bind 綁定
var bound = obj.increment.bind(obj);
bound();
// 3. 箭頭函式沿用外層 this(注意:箭頭函式沒有自己的 this)
var arrow = () => obj.increment();
arrow();
var test = { a: 1, b: "string", c: false, d: function(){ alert("OK"); } };
// 讀取
test.a test['a']
// 新增
test.e = 5
// 修改
test.a = 99
// 刪除
delete test.b
// 檢查是否存在
'a' in test // true
test.hasOwnProperty('a') // true(不查原型鏈)
// 遍歷
Object.keys(test) // ['a','c','d','e']
Object.entries(test) // [['a',1],['c',false],...]
如果多個物件都要同一個方法,把它掛在 prototype 上讓所有實例共享,比每個物件各自複製一份省記憶體:
function Person(name){
this.name = name; // 狀態放建構函數,每個實例獨立
}
Person.prototype.greet = function(){ // 方法放 prototype,全部共享
return '我是' + this.name;
};
new Person('小明').greet(); // 我是小明
ES6 的 class 語法背後就是這套機制:
class Person {
constructor(name){ this.name = name; }
greet(){ return `我是${this.name}`; } // 自動掛在 prototype 上
}
JavaScript 的物件觀念可以濃縮成三句話:物件是 key-value 的對照表;函式只是值的一種,所以可以當屬性、當參數、當回傳值;this 由呼叫方式決定,不由定義位置決定。把這三點想通, Closures、高階函式、原型鏈這些進階主題都會變得順暢。實務上還有一點值得牢記:需要動態決定屬性名稱時用中括號,其餘情況用點語法,程式碼會更清楚。