Search code examples
javascriptinstanceofsingle-instance

Making a javascript function that returns itself where it is an instance of itself


In Javascript, is it at all possible to make function Foo() such that both (Foo() == Foo), and (Foo() instanceof Foo)?

This almost works:

function Foo() { Object.setPrototypeOf(Foo,this); return Foo; }

so new Foo() instanceof Foo in this case, but if I just call Foo without new, it doesn't work.


Solution

  • You'll need to do

    function Foo() { return Foo; }             // Foo() === Foo
    Object.setPrototypeOf(Foo, Foo.prototype); // Foo instanceof Foo
    

    Remember that a instanceof B is equivalent to B.prototype.isPrototypeOf(a)