why typeof null
the result isObject
null是基本类型 而object 是引用类型 这样就会存在矛盾
Let's analyze this problem from the source code. Our JS is compiled by the V8 engine, so we need to debug V8
The installation tool node version should be higher
npm install -g jsvu
Install the V8 engine
jsvu --os=win64 --engines=v8-debug
//os 根据自己的操作系统选择
Switch to .jsvu under the user directory
Generate bytecode by the following command
v8-debug -e --print-bytecode --allow-natives-syntax "var x = xxxx"
Conclusions from generated bytecode
type of data | Machine code identifies the object |
(Object) | 000 |
integer | 1 |
floating point number | 010 |
string | 100 |
Boolean | 110 |
null |
all 0 |
Look at the source code of typeOf
JS_PUBLIC_API(JSType)
JS_TypeOfValue(JSContext *cx, jsval v)
{
JSType type = JSTYPE_VOID;
JSObject *obj;
JSObjectOps *ops;
JSClass *clasp;
CHECK_REQUEST(cx);
if (JSVAL_IS_VOID(v)) { // (1)
type = JSTYPE_VOID;
} else if (JSVAL_IS_OBJECT(v)) { // (2)
obj = JSVAL_TO_OBJECT(v);
if (obj &&
(ops = obj->map->ops,
ops == &js_ObjectOps
? (clasp = OBJ_GET_CLASS(cx, obj),
clasp->call || clasp == &js_FunctionClass) // (3,4)
: ops->call != 0)) { // (3)
type = JSTYPE_FUNCTION;
} else {
type = JSTYPE_OBJECT;
}
} else if (JSVAL_IS_NUMBER(v)) {
type = JSTYPE_NUMBER;
} else if (JSVAL_IS_STRING(v)) {
type = JSTYPE_STRING;
} else if (JSVAL_IS_BOOLEAN(v)) {
type = JSTYPE_BOOLEAN;
}
return type;
}
When judging the data type, it is judged according to the low-order flag of the machine code, and null
the machine code flag of is full 0
, and the low-order flag of the object's machine code is 000
. So typeof null
the result is misjudged asObject