Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why are null and undefined of the type DOMWindow?

When you run the following code in the browser, or in Node.js, you get the expected outcomes listed in the comments:

Object.prototype.toString.call(undefined); // "[object Undefined]"
Object.prototype.toString.call(null); // "[object Null]"

When you run that code in PhantomJS, however, the output is [object DOMWindow] in both cases.

This seems strange, since undefined and null are both native types. The typeof operator appears to work as it does in other environments (including the typeof null === "object" quirk), so it would appear that PhantomJS does at least have the concept of the undefined type:

typeof undefined; // "undefined"

It also claims that Object.prototype.toString contains native code, which may indicate that Phantom itself isn't doing anything to modify the implementation (I don't know if that's the case or not though - I haven't been able to find anything useful in the source):

Object.prototype.toString.toString(); // "function toString() { [native code] }"

So why does PhantomJS not use (or at least expose) the correct [[Class]] property values for null and undefined, and is there a way I change that? I know I could use a different method to determine type, but I'd rather not have to.

like image 479
James Allardice Avatar asked Jan 08 '13 15:01

James Allardice


People also ask

What is the value of typeof undefined === typeof null?

The typeof undefined is the string "undefined" — and undefined is a falsy value that is loosely equal to null but not to other falsy values.

Why is null an object in JavaScript?

The JavaScript specification says about null : null is a primitive value that represents the intentional absence of any object value. If you see null (either assigned to a variable or returned by a function), then at that place should have been an object, but for some reason, an object wasn't created.

What does object == null mean?

Its type is object . null is a special value meaning "no value. undefined is not an object, its type is undefined.

Why typeof null is object?

In JavaScript null is "nothing". It is supposed to be something that doesn't exist. Unfortunately, in JavaScript, the data type of null is an object. You can consider it a bug in JavaScript that typeof null is an object.


1 Answers

It is a combination of two things. A script is executed within a web page and therefore the global object is the window object, as evidenced from:

console.log(this.toString()); // [object DOMWindow]

In addition, there is a problem with that version of JavaScript implementation which falsifies the object prototype chain under the above condition.

This is likely going to be fixed in some future version.

like image 73
Ariya Hidayat Avatar answered Oct 26 '22 00:10

Ariya Hidayat