Skip to content Skip to sidebar Skip to footer

Reimplemented Constructor[symbol.hasinstance] But It Still Won't Be Called

So, I was writing some example code implementing another function for Constructor[Symbol.hasInstance] and I noticed my new implementation just won't get called. The script below is

Solution 1:

You can find the answer if you do

Object.getOwnPropertyDescriptor( Function.prototype, Symbol.hasInstance).writable

It returns false: you cannot write to the Symbol.hasInstance property of a function with the assignment = operator. The property never gets set and so it never gets called. (Failing silently feels like unhelpful behaviour to me, but there you go. A TypeError is thrown with a helpful message if you are in strict mode, one of the many reasons you should use it all the time.) You can only define the Symbol.hasInstance property on a function with Object.defineProperty.

Object.defineProperty(Pirate, Symbol.hasInstance, {
    value: function(anObj) {
        console.log('Is he a pirate?');
        return anObj.isPirate;
    }
});

Now jackSparrow instanceof Pirate first logs the question, then returns true.

Solution 2:

@lonesomeday's answer explains the reason. Assignments don't define a property if the object already inherits that property as non-writable.

If you don't want to use explicit property definitions, consider using the class syntax:

classPirate {
  constructor(name) {
    this.name = name;
  }
  static [Symbol.hasInstance](anObj) {
    return anObj.isPirate;
  }
}
const jackSparrow = {
  isPirate: true
};
console.log(jackSparrow instanceofPirate); // true

Post a Comment for "Reimplemented Constructor[symbol.hasinstance] But It Still Won't Be Called"