Search code examples
javascriptsymbols

Javascript Customising instanceof by well known symbol Symbol.hasInstance only work with [Symbol()] property


Following code example uses well known symbol Symbol.hasInstance to define static [Symbol.hasInstance](instance){...} function to customize instanceof behavior.

Basically, this function returns true if instance object has property [Forgeable.isMagic] defined. If that's the case then instance object is treated as if it is an instance of Forgeable class.

// This class allows plain objects to be disguised as this class's instance,
// as long as the object has [Forgeable.isMagic] as its property.
class Forgeable {
  static isMagic=Symbol();
  static isMagic2=Symbol();

  static [Symbol.hasInstance](instance) {
    return Forgeable.isMagic in instance;
  }
}

console.log('this object has static prop called isMagic', ({[Forgeable.isMagic]:'whatever'}) instanceof Forgeable);
console.log(({[Forgeable.isMagic2]:'whatever'}) instanceof Forgeable);
console.log(({}) instanceof Forgeable);

So I determined that our static prop isMagic is a Symbol.

My question is why does it need to be a Symbol for code to work? If I remove the Symbol assignment from isMagic then code doesn't work correctly. I think that's because undefined in {undefined:'blah'} returns true.

Actually, I tried static isMagic='blah' and this seems to work too. Maybe it just needed to be assigned a value? Just wanted to be sure.

My thinking is that it just needed to be assigned any value other than undefined. But I just want to be sure by feedback from others. I'm wondering because Symbol() was used in an example from MDN.

Thanks!

Note: this example is based from an example from https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/instanceof


Solution

  • Symbol() is used just because it is guaranteed to be unique. I could do without it in the above example.