Reputation: 1314
For some reason I came across a case where Chrome's V8 seems to think that an object is not actually an Object. I can't reproduce this easily but basically I have this code segment:
if (!(obj instanceof Object)) {
console.log(obj);
}
And yet chrome's console shows that it is in fact an Object... Does anyone know what could possibly cause this? How can I reproduce this?
WHen I use the typeof operator, it correctly identifies it as an object.
Upvotes: 2
Views: 575
Reputation: 74204
An object need not be an instance of Object
in JavaScript. For example:
var obj = Object.create(null);
console.log(obj instanceof Object); // false
console.log(typeof obj); // object
The reason for this is because of the way instanceof
is implemented. See the following answer for more details: https://stackoverflow.com/a/8096017/783743
Upvotes: 1
Reputation: 5971
The instanceof operator tests whether an object has in its prototype chain the prototype property of a constructor.
You can check Mozilla's developer site.
Basically the instanceof
operator evaulates to true if the object inherits from the classe's prototype, so for example:
var a = new Animal():
Here a is instance of Animal
since a
inherits from Animal.prototype
Upvotes: 0
Reputation: 152966
It may be from a different window
(e.g. an iframe), which has an own Object
constructor
var obj = frame.contentWindow.obj;
console.log(obj instanceof Object); // false
console.log(obj instanceof frame.contentWindow.Object); // true
Also note that there is a variety of objects in JS, including "Array objects", "RegExp objects", "Function objects", ... and "Object objects". The typeof
operator is not very helpful there. It can only distinguish between Function objects and other objects.
Upvotes: 4
Reputation: 39260
You're most likely dealing with a null value:
console.log(null instanceof Object);//false
console.log(typeof(null));// object
Or as Pumbaa80 commented; you got the object from an Iframe so it's constructor isn't the same Object as in the main window therefor instanceof Object is false but the variable does have an object value.
Upvotes: 0
Reputation: 5676
Typeof gives you the type of an object (in this case "object") and instanceof tests the prototype chain.
o={};
o instanceof Object //is true
typeof o // "object"
typeof(o.constructor.prototype)==="object" // is true
So in your case, the error has to be in the obj
.
Upvotes: 0
Reputation: 1414
This can happen if you override __proto__
. For example:
var myObj = { __proto__: null };
(myObject instanceof Object) === false;
This is due to how instanceof
works – it basically walks up the prototype chain looking for the constructor you passed to it. More information about instanceof
is available here.
Upvotes: 1