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 ?

1

2 Answers 2

1
subInst.__proto__ == inst.prototype
Sign up to request clarification or add additional context in comments.

1 Comment

Apparently, it's not good to use inst.constructor, how could I check the origin of inst in that case ?
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.

4 Comments

(new Example) instanceof Example; I got false with Chrome :/
@CyrilN. That is because /your/ Example function isn't a constructor, it's a factory function.
Ok, interesting! :) I need to to have a behavior like the one I used in my question. Is it the best way to do it or is there a better way?
Your code really doesn't make sense - using the new operator with a factory function has no effect.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.