Is null an object?

Possible duplicate:
Javascript null object

Is zero an object of law? So, if I set x to null, why can't I get the constructor value?

var x = null; alert(typeof x); alert(x.constructor); 
+6
javascript
source share
2 answers

null in JS is a primitive value. It was not constructed by any constructor function, so it does not have a constructor property. typeof null 'object' is basically a terrible lie, persisted for historical reasons. Do not expect too much consistency from JS, you will be disappointed!

Primitive values ​​can behave like objects in JS due to autoboxing: (1).constructor works even though 1 also a primitive value because it implicitly calls new Number(1) . But there is no null (or undefined ) object form for automatic conversion, so in this case you will get an error message.

In general, you should avoid using constructor . For many class / instance models built on top of JS, it does not do what you think at all. instanceof usually works better.

+11
source share

Null is not an object in Javascript - null is the only instance of the primitive type null and as such does not have a constructor.

0
source share

All Articles