Symbol.hasInstance and [[Get]] vs [[GetOwnProperty]]
/#!/JoePea
joe at trusktr.io
Tue Aug 16 01:45:07 UTC 2016
It seems like using [[Get]] for looking up `@@hasInstance` can be confusing
and requires devs to write extra code. For example, suppose we have the
following code:
```js
class A {
static [Symbol.hasInstance] (obj) {
return false
}
}
class B extends A {}
class C extends B {}
let c = new C
console.log(c instanceof B) // false, but expected true!
console.log(c instanceof A) // false, as expected
```
The `c instanceof B` check (arguably unintuitively) fails. Defining a
`Symbol.hasInstance` method on a base class causes `instanceof` checks on
any subclasses to automatically fail unless the developer takes care to
write an ugly and fragile workaround:
```js
class A {
static [Symbol.hasInstance](obj) {
if (this === A) return false
else return Function.prototype[Symbol.hasInstance].call(this, obj)
}
}
class B extends A {}
class C extends B {}
let c = new C
console.log(c instanceof B) // true, as expected
console.log(c instanceof A) // false, as expected
```
That seems likely to introduce errors or headaches.
What if the lookup for `Symbol.hasInstance` on an object use
[[GetOwnProperty]]? Then the first version without the conditional checks
would not break subclasses.
*/#!/*JoePea
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.mozilla.org/pipermail/es-discuss/attachments/20160815/2523c850/attachment.html>
More information about the es-discuss
mailing list