typeof 缺陷
- 无法正确区分
数组
和对象
- 前端经典:
typeof null === 'object'
无法区分 数据 和 对象
在V8 引擎 关于 typeof
的核心代码中,可以明显地看到,value
取出的instance_type
值能返回的label
只有
number
function
undefined
object
string
bigint
oddball
: 这玩意儿是下文的主体
在对instance_type
做判断的时候
这一句将 数组 和 对象 都返回成了 object
前端经典: typeof null === 'object'
这应该是一个历史遗留问题,可以看出编写v8的大神们也对这个null
有些头疼,将他的instace_type
命名成为了odd_ball
古怪的球? 笑~
原因:
-
Node* CodeStubAssembler::Typeof(Node* value)
中,使用
LoadMap
获得value
的map
-
Node* map = LoadMap(value);
使用
LoadMapInstanceType
获得instance_type
-
Node* instance_type = LoadMapIncetanceType(map)
为了避免使
null
和undefined
全等,所以提前做了一个判断,将null
的instance_type
返回成odd_type
-
GotoIf(InstanceTypeEqual(instance_type, ODDBALL_TYPE), &if_oddball);
随后更具
&return_xxx
来做绑定返回(类似switch
?) -
BIND(&return_number); { // HeapConstant(堆常数?) result_var.Bind(HeapConstant(isolate()->factory()->number_string())); Goto(&return_result); } BIND(&if_oddball); { //加载对象的文件??将 value(null)和Oddball::KTypeofoffset穿给这个方法函数??? //kType的抵消? //Oddball这个类重点kTypeoffset? Node* type = LoadObjectField(value, Oddball::kTypeOfOffset); result_var.Bind(type); Goto(&return_result); } BIND(&return_function); { result_var.Bind(HeapConstant(isolate()->factory()->function_string())); Goto(&return_result); } BIND(&return_undefined); { result_var.Bind(HeapConstant(isolate()->factory()->undefined_string())); Goto(&return_result); } BIND(&return_object); { result_var.Bind(HeapConstant(isolate()->factory()->object_string())); Goto(&return_result); } BIND(&return_string); { result_var.Bind(HeapConstant(isolate()->factory()->string_string())); Goto(&return_result); } BIND(&return_bigint); { result_var.Bind(HeapConstant(isolate()->factory()->bigint_string())); Goto(&return_result); }