Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript - instanceof not doing what I expect

Forgive me if I'm wrong, but I thought that by doing this:

function MyObject()
{
    return {
        key: 'value',
        hello: function() { console.log('world'); }
    };
}

var obj = new MyObject();

I create a new instance of the MyObject type.

However, if I do this:

obj instanceof MyObject

It returns false. This baffles me, as I thought that this would return true.

What am I doing wrong here?

Here's a fiddle that tests this.

I thought that I new the basics of JavaScript, but perhaps not. However, I've found sources that contradict my findings.

like image 381
Boom Avatar asked Mar 19 '16 22:03

Boom


1 Answers

If you explicitly return an object from a constructor function (as you do here) then you get that object instead of an instance of the constructor.

If you wanted to get an instance of the constructor, then you would do this:

function MyObject()
{
    this.key = 'value';
    this.hello = function() { console.log('world'); };
}

(Although, in general, you'd want to put methods on the prototype instead of generating duplicates of them each time you construct a new instance).

like image 74
Quentin Avatar answered Sep 20 '22 20:09

Quentin