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

相关文章
相关标签/搜索