klewis
klewis

Reputation: 8340

Understanding instanceof with JavaScript

I have a basic understanding of instanceof in JavaScript, testing if the left hand side object "is of" the right hand side object type. The following 2 examples help me understand that...

var demo1 = function() {};
demo1.prototype = {
foo: "hello"
};

var demo2 = function() {
var pub = {
    bar:"world"
};
return this.pub;
};

var obj1 = new demo1();
var obj2 = new demo2();

console.log(obj1 instanceof demo1);  //returns true
console.log(obj2 instanceof demo2);  //returns true

But on this 3rd example, I get false and I don't understand why....

var o = {}; // new Object;
o.toString(); // [object Object]
console.log(o instanceof toString); //returns false

Thanks for any help in understanding whats going on. Also...is is possible to make the 3rd example true?

Thanks again

Upvotes: 0

Views: 3894

Answers (3)

Bergi
Bergi

Reputation: 664164

toString does not cause a type change of o. It just returns a string representation of the object, without altering it. So, o is still a simple object and no instanceof String.

var o = {}; // new Object object
var ostring = o.toString(); // "[object Object]"
typeof o; // object
typeof ostring; // string - this is a primitive value, not an object; so that
ostring instanceof String; // is false
var stringobj = new String(ostring); // new String object
typeof stringobj; // object
stringobj instanceof String; // true!
o instanceof Object; // also true!

See also MDN reference for the String constructor.

Upvotes: 4

David Hoerster
David Hoerster

Reputation: 28701

o is an object; toString is a function. They are different types in JavaScript.

alert(typeof(o));  //"object"
alert(typeof(toString)); //"function"

JavaScript makes a distinction between objects and functions. Therefore, that's why you get false returned in your example.

Upvotes: 1

Ingo Kegel
Ingo Kegel

Reputation: 47965

With an object literal like

var o = {}; // new Object;

you create an object whose prototype is Object. Testing with instanceof will not yield any useful information. The only comparison that will yield true is

o instanceof Object

Upvotes: 1

Related Questions