Cyril N.
Cyril N.

Reputation: 39889

How to check the instanceof an instance of an object in Javascript

I'm working on a JavaScript and I got stuck with some verification :

I'd like to check that the variable given as a parameter was an instance of an instance of an object. To be more clear, here's an example :

var Example = function () {
    console.log ('Meta constructor');
    return function () {
        console.log ('Instance of the instance !');
    };
};

var inst = new Example();
assertTrue(inst instanceof Example.constructor); // ok

var subInst = new inst();
assertTrue(subInst instanceof Example.constructor); // FAIL
assertTrue(subinst instanceof inst.constructor); // FAIL

How can I check that subInst is an instance of Example.{new} ? or inst.constructor ?

Upvotes: 1

Views: 428

Answers (2)

Delta
Delta

Reputation: 4328

subInst.__proto__ == inst.prototype

Upvotes: 1

Sean Kinsey
Sean Kinsey

Reputation: 38046

First of all, you don't check against .constructor, you check against the constructing function, that is Example. Whenever you're testing the .constructor property, this will be the one found on the instance (if you set it on the prototype of the constructor).

So

(new Example) instanceof Example; // true

Secondly, if your Example function is returning a function, then Example isn't actually a constructor, and hence you can not do any kind of prototypical inheritance checks on it. A constructor will always return an object, and that object will be an instance of the constructor.

What you have is instead a factory function that creates functions that might be used as a constructor. A function will only pass instanceof checks for Function and Object.

var Ctor = example(); // PascalCase constructor, camelCase factory
var inst = new Ctor();
inst instanceof Ctor; // true

But do take a look at the link posted by @franky, it should give you some insights into what you need to do.

Upvotes: 1

Related Questions