1 概述
規格檔案是計算機語言的官方标準,較長的描述文法規則和實作方法。
一般來說,沒有必要閱讀規格,除非你要寫編譯器。因為規格寫得非常抽象和精煉,又缺乏執行個體,不容易了解,而且對于解決實際的應用問題,幫助不大。但是,如果你遇到疑難的文法問題,實在找不到答案,這時可以去檢視規格檔案,了解語言标準是怎麼說的。規格是解決問題的 “ 最後一招 ” 。
這對 JavaScript 語言很有必要。因為它的使用場景複雜,文法規則不統一,例外很多,各種運作環境的行為不一緻,導緻奇怪的文法問題層出不窮,任何文法書都不可能囊括所有情況。檢視規格,不失為一種解決文法問題的最可靠、最權威的終極方法。
本章介紹如何讀懂 ECMAScript 6 的規格檔案。
ECMAScript 6 的規格,可以在 ECMA 國際标準組織的官方網站( www.ecma-international.org/ecma-262/6.0/ )免費下載下傳和線上閱讀。
這個規格檔案相當龐大,一共有 26 章, A4 列印的話,足足有 545 頁。它的特點就是規定得非常細緻,每一個文法行為、每一個函數的實作都做了詳盡的清晰的描述。基本上,編譯器作者隻要把每一步翻譯成代碼就可以了。這很大程度上,保證了所有 ES6 實作都有一緻的行為。
ECMAScript 6 規格的 26 章之中,第 1 章到第 3 章是對檔案本身的介紹,與語言關系不大。第 4 章是對這門語言總體設計的描述,有興趣的讀者可以讀一下。第 5 章到第 8 章是語言宏觀層面的描述。第 5 章是規格的名詞解釋和寫法的介紹,第 6 章介紹資料類型,第 7 章介紹語言内部用到的抽象操作,第 8 章
介紹代碼如何運作。第 9 章到第 26 章介紹具體的文法。
對于一般使用者來說,除了第 4 章,其他章節都涉及某一方面的細節,不用通讀,隻要在用到的時候,查閱相關章節即可。下面通過一些例子,介紹如何使用這份規格。
2 相等運算符
相等運算符(==)是一個很讓人頭痛的運算符,它的文法行為多變,不符合直覺。這個小節就看看規格怎麼規定它的行為。
請看下面這個表達式,請問它的值是多少。
0 == null
如果你不确定答案,或者想知道語言内部怎麼處理,就可以去檢視規格, 對相等運算符(==)的描述。
規格對每一種文法行為的描述,都分成兩部分:先是總體的行為描述,然後是實作的算法細節。相等運算符的總體描述,隻有一句話。
“The comparison x == y , where x and y are values, produces true or false .”
上面這句話的意思是,相等運算符用于比較兩個值,傳回true或false。
下面是算法細節。
1. ReturnIfAbrupt(x).
2. ReturnIfAbrupt(y).
3. If Type(x) is the same as Type(y) , then
Return the result of performing Strict Equality Comparison x === y .
4. If x is null and y is undefined , return true .
5. If x is undefined and y is null , return true .
6. If Type(x) is Number and Type(y) is String,
return the result of the comparison x == ToNumber(y) .
7. If Type(x) is String and Type(y) is Number,
return the result of the comparison ToNumber(x) == y .
8. If Type(x) is Boolean, return the result of the comparison ToNumber(x) == y .
9. If Type(y) is Boolean, return the result of the comparison x == ToNumber(y) .
10. If Type(x) is either String, Number, or Symbol and Type(y) is Object, then
return the result of the comparison x == ToPrimitive(y) .
11. If Type(x) is Object and Type(y) is either String, Number, or Symbol, then
return the result of the comparison ToPrimitive(x) == y .
12. Return false .
上面這段算法,一共有 12 步,翻譯如下。
1. 如果x不是正常值(比如抛出一個錯誤),中斷執行。
2. 如果y不是正常值,中斷執行。
3. 如果Type(x)與Type(y)相同,執行嚴格相等運算x === y。
4. 如果x是null,y是undefined,傳回true。
5. 如果x是undefined,y是null,傳回true。
6. 如果Type(x)是數值,Type(y)是字元串,傳回x == ToNumber(y)的結果。
7. 如果Type(x)是字元串,Type(y)是數值,傳回ToNumber(x) == y的結果。
8. 如果Type(x)是布爾值,傳回ToNumber(x) == y的結果。
9. 如果Type(y)是布爾值,傳回x == ToNumber(y)的結果。
10. 如果Type(x)是字元串或數值或Symbol值,Type(y)是對象,傳回x == ToPrimitive(y)的結果。
11. 如果Type(x)是對象,Type(y)是字元串或數值或Symbol值,傳回ToPrimitive(x) == y的結果。
12. 傳回false。
由于0的類型是數值,null的類型是 Null (這是規格 4.3.13 小節的規定,是内部 Type 運算的結果,跟typeof運算符無關)。是以上面的前 11 步都得不到結果,要到第 12 步才能得到false。
0 == null // false
3 數組的空位
下面再看另一個例子。
const a1 = [undefined, undefined, undefined];
const a2 = [, , ,];
a1.length // 3
a2.length // 3
a1[0] // undefined
a2[0] // undefined
a1[0] === a2[0] // true
上面代碼中,數組a1的成員是三個undefined,數組a2的成員是三個空位。這兩個數組很相似,長度都是 3 ,每個位置的成員讀取出來都是undefined。
但是,它們實際上存在重大差異。
0 in a1 // true
0 in a2 // false
a1.hasOwnProperty(0) // true
a2.hasOwnProperty(0) // false
Object.keys(a1) // ["0", "1", "2"]
Object.keys(a2) // []
a1.map(n => 1) // [1, 1, 1]
a2.map(n => 1) // [, , ,]
上面代碼一共列出了四種運算,數組a1和a2的結果都不一樣。前三種運算(in運算符、數組的hasOwnProperty方法、Object.keys方法)都說明,數組a2取不到屬性名。最後一種運算(數組的map方法)說明,數組a2沒有發生周遊。
為什麼a1與a2成員的行為不一緻?數組的成員是undefined或空位,到底有什麼不同?
規格的 12.2.5 小節《數組的初始化》給出了答案。
“Array elements may be elided at the beginning, middle or end of the element list. Whenever a comma in the element list is not preceded by an AssignmentExpression (i.e., a comma at the beginning or after another comma), the missing array element contributes to the length of the Array and increases the index of subsequent elements. Elided array elements are not defined. If an element is elided at the end of an array, that element does not contribute to the length of the Array.”
翻譯如下。
" 數組成員可以省略。隻要逗号前面沒有任何表達式,數組的length屬性就會加 1 ,并且相應增加其後成員的位置索引。被省略的成員不會被定義。如果被省略的成員是數組最後一個成員,則不會導緻數組length屬性增加。 "
上面的規格說得很清楚,數組的空位會反映在length屬性,也就是說空位有自己的位置,但是這個位置的值是未定義,即這個值是不存在的。如果一定要讀取,結果就是undefined(因為undefined在 JavaScript 語言中表示不存在)。
這就解釋了為什麼in運算符、數組的hasOwnProperty方法、Object.keys方法,都取不到空位的屬性名。因為這個屬性名根本就不存在,規格裡面沒說要為空位配置設定屬性名 ( 位置索引),隻說要為下一個元素的位置索引加 1 。
至于為什麼數組的map方法會跳過空位,請看下一節。
4 數組的 map 方法
規格的 22.1.3.15 小節定義了數組的map方法。該小節先是總體描述map方法的行為,裡面沒有提到數組空位。
後面的算法描述是這樣的。
1. Let O be ToObject(this value) .
2. ReturnIfAbrupt(O) .
3. Let len be ToLength(Get(O, "length")) .
4. ReturnIfAbrupt(len) .
5. If IsCallable(callbackfn) is false , throw a TypeError exception.
6. If thisArg was supplied, let T be thisArg ; else let T be undefined .
7. Let A be ArraySpeciesCreate(O, len) .
8. ReturnIfAbrupt(A) .
9. Let k be 0.
10. Repeat, while k < len
a. Let Pk be ToString(k) .
b. Let kPresent be HasProperty(O, Pk) .
c. ReturnIfAbrupt(kPresent) .
d. If kPresent is true , then
d-1. Let kValue be Get(O, Pk) .
d-2. ReturnIfAbrupt(kValue) .
d-3. Let mappedValue be Call(callbackfn, T, «kValue, k, O») .
d-4. ReturnIfAbrupt(mappedValue) .
d-5. Let status be CreateDataPropertyOrThrow (A, Pk, mappedValue) .
d-6. ReturnIfAbrupt(status) .
e. Increase k by 1.
11. Return A .
翻譯如下。
1. 得到目前數組的this對象
2. 如果報錯就傳回
3. 求出目前數組的length屬性
4. 如果報錯就傳回
5. 如果 map 方法的參數callbackfn不可執行,就報錯
6. 如果 map 方法的參數之中,指定了this,就讓T等于該參數,否則T為undefined
7. 生成一個新的數組A,跟目前數組的length屬性保持一緻
8. 如果報錯就傳回
9. 設定k等于 0
10. 隻要k小于目前數組的length屬性,就重複下面步驟
a. 設定Pk等于ToString(k),即将K轉為字元串
b. 設定kPresent等于HasProperty(O, Pk),即求目前數組有沒有指定屬性
c. 如果報錯就傳回
d. 如果kPresent等于true,則進行下面步驟
d-1. 設定kValue等于Get(O, Pk),取出目前數組的指定屬性
d-2. 如果報錯就傳回
d-3. 設定mappedValue等于Call(callbackfn, T, «kValue, k, O»),即執行回調函數
d-4. 如果報錯就傳回
d-5. 設定status等于CreateDataPropertyOrThrow (A, Pk, mappedValue),即将回調函數的值放入A數組的指定位置
d-6. 如果報錯就傳回
e. k增加 1
11. 傳回A
仔細檢視上面的算法,可以發現,當處理一個全是空位的數組時,前面步驟都沒有問題。進入第 10 步的 b 時,kpresent會報錯,因為空位對應的屬性名,對于數組來說是不存在的,是以就會傳回,不會進行後面的步驟。
const arr = [, , ,];
arr.map(n => {
console.log(n);
return 1;
}) // [, , ,]
上面代碼中,arr是一個全是空位的數組,map方法周遊成員時,發現是空位,就直接跳過,不會進入回調函數。是以,回調函數裡面的console.log語句根本不會執行,整個map方法傳回一個全是空位的新數組。
V8 引擎對map方法的實作如下,可以看到跟規格的算法描述完全一緻。
function ArrayMap(f, receiver) {
CHECK_OBJECT_COERCIBLE(this, "Array.prototype.map");
// Pull out the length so that modifications to the length in the
// loop will not affect the looping and side effects are visible.
var array = TO_OBJECT(this);
var length = TO_LENGTH_OR_UINT32(array.length);
return InnerArrayMap(f, receiver, array, length);
}
function InnerArrayMap(f, receiver, array, length) {
if (!IS_CALLABLE(f)) throw MakeTypeError(kCalledNonCallable, f);
var accumulator = new InternalArray(length);
var is_array = IS_ARRAY(array);
var stepping = DEBUG_IS_STEPPING(f);
for (var i = 0; i < length; i++) {
if (HAS_INDEX(array, i, is_array)) {
var element = array[i];
// Prepare break slots for debugger step in.
if (stepping) %DebugPrepareStepInIfStepping(f);
accumulator[i] = %_Call(f, receiver, element, i, array);
}
}
var result = new GlobalArray();
%MoveArrayContents(accumulator, result);
return result;
}