Strawman proposal: new `is` operator

C. Scott Ananian ecmascript at cscott.net
Sun Aug 24 13:15:21 PDT 2014


On Sun, Aug 24, 2014 at 4:04 PM, Isiah Meadows <impinball at gmail.com> wrote:
> There is no way currently to reliably verify types in JS. Type annotations
> cannot solve this completely, especially when you have an overloaded
> function. A way to reliably verify types would make this far easier. So far,
> here are the current options with their respective caveats:
>
> 1. `instanceof` - This returns true for the class, but also for subclasses.
> This isn't always desired.

Your proposal fixes this, but does not address the other issues you raise:

> 2. `this.constructor === Foo` - The constructor property could easily be
> overwritten, rendering this relatively useless.

`Object.getPrototypeOf(this) === Foo.prototype` is the test which
`instanceof` uses.
Does not require new syntax.

> 3. `typeof` - This only is useful for literals, with the exception of
> `null`.

Your proposed `is` operator is not useful for literals.

> 4. `Object.prototype.toString.call()` - This returns the correct native
> object type for native objects, but returns `[object Object]` for all
> non-native objects, rendering it effectively useless. This includes object
> instances created from `class Foo {}`, etc.

In general, you can always define:
```
Object.prototype.is = function(constructor) {
  return Object.getPrototypeOf(this) === constructor.prototype;
};
```
rather than try to use toString.  Unless you want it to work on literals...
  --scott


More information about the es-discuss mailing list