trusktr
trusktr

Reputation: 45504

Why can I not assign Symbol.hasInstance onto a function?

I have the following code:

function A() {
}

A[Symbol.hasInstance] = function(i) {return true}

It fails with an error in my Webpack+Babel environment:

Uncaught TypeError: Cannot assign to read only property 'Symbol(Symbol.hasInstance)' of function 'function A() {}'

Why?

Upvotes: 2

Views: 1109

Answers (1)

trusktr
trusktr

Reputation: 45504

The reason is because the property descriptor for Function.prototype[Symbol.hasInstance] has {writable: false}, which makes it not possible to assign in that manner. The JS engine looks up the Function.prototype[Symbol.hasInstance] descriptor, sees writable: false, then forbids the assignment even if it is being assigned on a leaf object of the prototype type rather than on the original object where the property was found, or in other words, the writable: false property is prototypically inherited even though the property does not yet exist on the leaf-most object of the prototype chain where we are trying to assign the value.

To get around the issue, we can use Object.defineProperty, which works just fine:

function A() {
}

Object.defineProperty(A, Symbol.hasInstance, {
  value: function(i) {return true}
})

Upvotes: 5

Related Questions