1

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.

markt1964
  • 2,638
  • 2
  • 22
  • 54
  • 1
    why would you want to do that? – gp. May 03 '17 at 01:21
  • `Object.setPrototypeOf(Foo,this);` sets *Foo*'s prototype to an instance of *Foo*, which still has the original *Foo* prototype as its `[[Prototype]]` (because it was constructed before you swapped the prototype). Subsequent calls will keep inserting new objects on the prototype chain. Messy. Call it without *new* and things really go to pot! – RobG May 03 '17 at 01:38

1 Answers1

3

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)

Bergi
  • 630,263
  • 148
  • 957
  • 1,375
  • 3
    And of course, please never use this anywhere for real… – Bergi May 03 '17 at 01:51
  • @RobG [`isProtototypeOf`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/isPrototypeOf) also searches the chain – Bergi May 03 '17 at 12:05
  • Hmm, one day I'll work out how to read the spec, or it will be written in a way that is reasonably understandable… – RobG May 03 '17 at 23:30