本文要談的是 ECMAScript 2015(ES6)的知識點。若連 ES5 都還不熟,那確實該加快腳步了。
有些時候我們需要把一個陣列「攤開」成多個參數傳給函式。ES5 時代靠 Function.prototype.apply 可以辦到,但它無法與 new 協同運作。本文說明了展開(spread)是什麼,以及如何在搭配 new 的情況下完成展開。
展開指的是:在函式呼叫、方法呼叫或建立物件時,用一個陣列來提供所需的參數。Python 稱之為 unpacking。ES6 提供了展開運算子(前綴 ...)來執行這件事;在現行的 JavaScript 中,則可用 Function.prototype.apply 達到同樣效果。
補充:展開運算子除了用在實參位置把陣列攤開,也能用在形參位置表示剩餘參數(rest parameters)。
Math.max() 回傳其任意多個數值參數中的最大值。有了展開運算子,可以直接傳入一個陣列:
Math.max(...[13, 7, 30]); // 等同於 Math.max(13, 7, 30)
ES5 的寫法是用 apply:
> Math.max.apply(null, [13, 7, 30])
30
apply 的作用是讓下面這種呼叫:
func.apply(thisValue, [param1, param2, ...])
等同於:
func(param1, param2, ...)
要注意的是,func 不一定是 thisValue 的方法,apply 讓它臨時擁有了這個方法。
Date 建構子接受數個數值參數來產生日期物件。用展開運算子可以直接傳陣列:
new Date(...[2011, 11, 24]); // 2011 年的聖誕夜
但這裡不能用 apply,因為它無法與 new 一起工作:
> new Date.apply(null, [2011, 11, 24])
TypeError: function apply() { [native code] } is not a constructor
new 期望 Date.apply 是一個建構子。就算用括號包住整個運算式也沒用——apply 執行的是一次函式呼叫,無法把參數傳遞給 new。
先讓結果正確,稍後再想辦法用陣列取代分開寫的參數:
new (Date.bind(null, 2011, 11, 24))()
我們先用 bind() 建立一個參數已綁定的新函式,再用 new 呼叫它。bind 的簽名是:
func.bind(thisValue, arg1, arg2, ...)
它會回傳一個全新的函式,其 this 永遠是 thisValue,且初始參數包含 arg1 之後的所有值;之後呼叫新函式時,新傳入的參數會接在既有參數之後。此處第一個參數是 null,因為 Date 不需要 this——作為建構子呼叫時,new 會覆蓋掉 bind 指定的 this。
new (Function.prototype.bind.apply(
Date, [null].concat([2011, 11, 24])))()
我們在 Function.prototype.bind 上呼叫 apply,傳入兩個參數:
Date,等同於 Date.bind(...)。null 與陣列 [2011, 11, 24] 串接後的新陣列,作為 bind 的參數。Mozilla 建議把上述做法包成一個方法,以下是在其建議上略作修改的版本:
if (!Function.prototype.construct) {
Function.prototype.construct = function (argArray) {
if (!Array.isArray(argArray)) {
throw new TypeError("Argument must be an array");
}
var constr = this;
var nullaryFunc = Function.prototype.bind.apply(
constr, [null].concat(argArray));
return new nullaryFunc();
};
}
> Date.construct([2011, 11, 24])
Sat Dec 24 2011 00:00:00 GMT+0100 (CET)
也可以手動模擬 new 的行為:
var foo = new Foo("abc");
等同於:
var foo = Object.create(Foo.prototype);
Foo.call(foo, "abc");
依此原理可寫出更簡短的庫方法:
Function.prototype.construct = function (argArray) {
var constr = this;
var inst = Object.create(constr.prototype);
constr.apply(inst, argArray);
return inst;
};
但 Date 作為普通函式呼叫與作為建構子呼叫的行為完全不同:不加 new 時,不論有無參數,Date() 只會回傳當前時間的字串,等同於 (new Date()).toString()。因此這個版本會得到意外的結果:
> Date.construct([2011, 11, 24])
{}
內建的建構子中,Array()、Function()、RegExp()、Error() 加不加 new 幾乎一樣;但 Number()、String()、Boolean() 完全不同——不加 new 是型別轉換函式,回傳原始值;加 new 是建構子,回傳物件:
> typeof Number("1")
"number"
> typeof new Number("1")
"object"
此外,任何建構子只要 return 的是物件值,就會覆蓋預設產生的 this:
function Func1() { this.value = "this"; return {}; } // 回傳 {},覆蓋 this
function Func2() { this.value = "this"; return 1; } // 回傳原始值,仍回傳 this
function Func3() { this.value = "this"; } // 無 return,仍回傳 this
> new Func1() // {}
> new Func2() // { value: "this" }
> new Func3() // { value: "this" }
因此 3.4 的寫法只在操作自訂建構子時大致可行;若某建構子自行回傳了物件,行為就會與預期不同。ES6 之後,直接用 new (Function.prototype.bind.apply(...)) 或改用 Reflect.construct 才是正解。