关于null的typeof和instanceof

来源:互联网 发布:xp添加网络打印机 url 编辑:程序博客网 时间:2024/06/11 16:06

问题:

alert(typeof(null)); //objectalert(null instanceof Object); //false

答案:

这是由Javascript规范规定的,Null和Object都是javascript中的数据类型。
Null数据类型只有一个值:null。就像undefined数据类型只有一个值:undefined。
问题出在typeof操作符的定义规范,如下:

11.4.3 The typeof OperatorThe production UnaryExpression : typeof UnaryExpression is evaluated as follows:1. Evaluate UnaryExpression.2. If Type(Result(1)) is not Reference, go to step 4.3. If GetBase(Result(1)) is null, return "undefined".4. Call GetValue(Result(1)).5. Return a string determined by Type(Result(4)) according to the following table:Type ResultUndefined "undefined"Null "object"Boolean "boolean"Number "number"String "string"Object (native anddoesn’t implement[[Call]])"object"Object (native andimplements [[Call]])"function"Object (host) Implementation-dependent

可以看到,对于Null类型的值(只有null),规范就是定义返回”object”这个字符串。但是本质上Null和Object不是一个数据类型,null值并不是以Object为原型创建出来的。所以null instanceof Object是false。但从这里也可以看到,null确实是javascript中用来表示空引用的一个特殊值。使得它不是instanceof Ojbect,而typeof null是“object”。在语义上也是可以理解的。


参考链接:null的type和instanceof求解

0 0
原创粉丝点击