Fixing the associativity / precedence of the instanceof operator

Andrea Giammarchi andrea.giammarchi at gmail.com
Tue Aug 26 08:22:01 PDT 2014


I sort of like the `!` not operation as `!instanceof` in order to both `obj
instanceof(Object)` and `obj !instanceof(Object)` but I find other ideas
not so bad too, here a couple of examples:

```js
// via Objects
Object.defineProperty(
  Object.prototype,
  'instanceOf',
  {
    enumerable: false,
    configurable: true,
    writable: true,
    value: function (Constructor) {
      return this instanceof Constructor;
    }
  }
);

console.log({}.instanceOf(Object));  // true
console.log(!{}.instanceOf(Object)); // false

// via constructors
Object.defineProperty(
  Function.prototype,
  'isInheritedBy',
  {
    enumerable: false,
    configurable: true,
    writable: true,
    value: function (obj) {
      return obj instanceof this;
    }
  }
);

console.log(Object.isInheritedBy({}));   // true
console.log(!Object.isInheritedBy({}));  // false

console.log(Object.isInheritedBy(
  Object.create(null)
));   // false
```

Regards



On Tue, Aug 26, 2014 at 3:02 PM, Nathan Wall <wwall at google.com> wrote:

> An `isnt` operator has been proposed before[1].
>
> Parens are ugly. Proto[2] supports negating operators with `!` (`foo !in
> bar`, `foo !is bar`, `foo !like bar`).
>
>
> [1] http://wiki.ecmascript.org/doku.php?id=harmony:egal
> [2] https://github.com/Nathan-Wall/proto
>
>
>
>
> On Mon, Aug 25, 2014 at 6:40 AM, Charles Pick <charles at codemix.com> wrote:
>
>> Hello, forgive me if this has come up before, I couldn't find any
>> discussions via Google.
>>
>> One regular, annoying mistake I see people making is combining the `!`
>> operator with `instanceof`:
>>
>>     if (!foo instanceof Foo) { ... }
>>
>>
>> of course, this must be written with extra parentheses:
>>
>>     if (!(foo instanceof Foo)) { ... }
>>
>>
>> My question is, why? There are no circumstances where the developer
>> *intended* to write the first version, it's a typo and will always evaluate
>> to false, even when using Boolean. Therefore would it be possible to fix
>> the precedence so that the first version is parsed the same way as the
>> second?
>>
>>
>> Regards,
>>
>> Charles
>>
>> _______________________________________________
>> es-discuss mailing list
>> es-discuss at mozilla.org
>> https://mail.mozilla.org/listinfo/es-discuss
>>
>>
>
> _______________________________________________
> es-discuss mailing list
> es-discuss at mozilla.org
> https://mail.mozilla.org/listinfo/es-discuss
>
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.mozilla.org/pipermail/es-discuss/attachments/20140826/c0a1e287/attachment.html>


More information about the es-discuss mailing list