ToPrimitive 內部邏輯標準

ToPrimitive 是包含兩個參數的抽象的操做,一個是 input argument 參數,一個是可選參數 PreferredType,該操做就是將 input argument 轉換爲 no-Object type (非 object 類型的值,即js數據類型的5種普通類型)。
爲何第二個參數是可選參數,由於在一些必要的狀況下須要傳入該參數。
在第一個參數爲 object 時,ToPrimitive 有可能將該 object 轉換不止一種基本類型的值。
可選參數 hint PreferredType 肯定地將其轉換爲一種類型
input argument 轉換爲 non-Object type 遵循下表
input Type Result
Undefined input argument
Null input argument
Boolean input argument
Number input argument
String input argument
Object 忽略 第二個參數 hint PreferredType 直接調用內置方法 [[DefaultValue]]

[[DefaultValue]]

標準裏提到,分別攜帶參數 "toString"/"valueOf" 調用內置方法 [[Get]] 獲取傳入的參數,再經過調用 IsCallable 方法判斷其是否有 [[call]] 方法採起調用 [[call]] 再次拿到 primitiveValuegit

通俗地理解就是,分類討論 + 遞歸調用,將全部的 Object 轉換爲 non-Object github

參考:
http://es5.github.io/#x9.1
http://es5.github.io/#x8.12.8
http://es5.github.io/#x9.11es5

相關文章
相關標籤/搜索