1

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 ?

halfer
  • 19,824
  • 17
  • 99
  • 186
Cyril N.
  • 38,875
  • 36
  • 142
  • 243
  • 1
    Check this out http://stackoverflow.com/questions/2449254/what-is-the-instanceof-operator-in-javascript – TheITGuy Oct 22 '12 at 07:25

2 Answers2

1

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.

Sean Kinsey
  • 37,689
  • 7
  • 52
  • 71
1
subInst.__proto__ == inst.prototype
Delta
  • 4,308
  • 2
  • 29
  • 37
  • Apparently, it's not good to use inst.constructor, how could I check the origin of inst in that case ? – Cyril N. Oct 22 '12 at 16:09