why is typeof null “object”?

2018-12-31 09:06发布

I am reading 'Professional Javascript for Web Developers' Chapter 4 and it tells me that the five types of primitives are: undefined, null, boolean, number and string.

If null is a primitive, why does typeof(null) return "object"?

Wouldn't that mean that null is passed by reference (I'm assuming here all objects are passed by reference), hence making it NOT a primitive?

5条回答
浪荡孟婆
2楼-- · 2018-12-31 09:26

In the first implementation of JavaScript, JavaScript values were represented as a type tag and a value, with the type tag for objects being 0, and null was represented as the NULL pointer (0x00 on most platforms). As a result, null had 0 as a type tag, hence the bogus typeof return value (reference).

 typeof null === 'object'; // This stands since the beginning of JavaScript

A "fix" was proposed for ECMAScript (via an opt-in). It would have resulted in:

typeof null === 'null'

... but this change was rejected, due to issues with code using this specific "quirk" to test for null.

查看更多
倾城一夜雪
3楼-- · 2018-12-31 09:30

If null is a primitive, why does typeof(null) return "object"?

Because the spec says so.

11.4.3 The typeof Operator

The production UnaryExpression : typeof UnaryExpression is evaluated as follows:

  1. Let val be the result of evaluating UnaryExpression.
  2. If Type(val) is Reference, then
       a. If IsUnresolvableReference(val) is true, return "undefined".
       b. Let val be GetValue(val).
  3. Return a String determined by Type(val) according to Table 20.

enter image description here

查看更多
柔情千种
4楼-- · 2018-12-31 09:39

If null is a primitive, why does typeof(null) return "object"?

in short: it is bug in ECMAScript, and the type should be null

reference: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/null

查看更多
高级女魔头
5楼-- · 2018-12-31 09:40

From the book YDKJS

This is a long-standing bug in JS, but one that is likely never going to be fixed. Too much code on the Web relies on the bug and thus fixing it would cause a lot more bugs!

查看更多
无与为乐者.
6楼-- · 2018-12-31 09:41

As has been pointed out, the spec says so. But since the implementation of JavaScript predates the writing of the ECMAScript spec, and the specification was careful not to correct foibles of the initial implementation, there's still a legitimate question about why it was done this way in the first place. Douglas Crockford calls it a mistake. Kiro Risk thinks it kinda sorta makes sense:

The reasoning behind this is that null, in contrast with undefined, was (and still is) often used where objects appear. In other words, null is often used to signify an empty reference to an object. When Brendan Eich created JavaScript, he followed the same paradigm, and it made sense (arguably) to return "object". In fact, the ECMAScript specification defines null as the primitive value that represents the intentional absence of any object value (ECMA-262, 11.4.11).

查看更多
登录 后发表回答