1

So I am running this code

function somefunc() { 
    return new WeakMap(); 
}

somefunc.prototype = new WeakSet();

var wm = new somefunc();

wm instanceof WeakMap //true
wm instanceof WeakSet //false

I wanted to ask why isn't wm an instance of WeakSet, because according to the example given here, wm should be an instance of Weakset.

Andrew Li
  • 55,805
  • 14
  • 125
  • 143
  • Your `somefunc` is not a constructor - it returns an object – Bergi Oct 10 '16 at 16:26
  • @Bergi so if a function return an object it is not a constructor ? – John Coder Oct 10 '16 at 19:15
  • Yes, we call that a factory function. `wm` is the weak map created by `new WeakMap()`, despite being returned from the expression `new somefunc()`. Just doing `wm = somefunc()` would have exactly the same result – Bergi Oct 10 '16 at 19:32
  • So is there anyway i can tweak this code to make wm an instanceof WeakSet ? – John Coder Oct 11 '16 at 09:10
  • There are many ways, but they will all alter the behaviour. You cannot have a `WeakMap` that is also an instance of `WeakSet`. – Bergi Oct 11 '16 at 13:29
  • Could you please point me towards the ways, behaviour alteration is ok. i just need the WeakMap to also be an instance of WeakSet – John Coder Oct 12 '16 at 08:25
  • Just drop the `return new WeakMap();` and instead create some properties (`this.foo = "bar";`). "*I need the WeakMap to also be an instance of WeakSet*" - as I just said, that's impossible. There is no multiple inheritance in JavaScript. An object cannot be both a `WeakMap` and a `WeakSet`. Maybe you should [ask a new question](http://stackoverflow.com/questions/ask) stating what problem you actually trying to solve. – Bergi Oct 12 '16 at 10:38

0 Answers0