Determining if an object can be constructed

Isiah Meadows isiahmeadows at gmail.com
Tue Jan 24 18:57:06 UTC 2017


Yeah, I'm aware. I'm keeping my previous "prototype with a specific method"
this time around. Much easier IMHO.

On Tue, Jan 24, 2017, 13:47 Claude Pache <claude.pache at gmail.com> wrote:

>
> > Le 24 janv. 2017 à 19:12, Isiah Meadows <isiahmeadows at gmail.com> a
> écrit :
> >
> > To clarify, I'm wanting to know if it's a callable that isn't a class.
> > Technically, I could use `Function.prototype.toString` for most
> > practical purposes of mine, but that'd be super slow (I'd need it in a
> > warm loop), and wouldn't catch native construct-only classes like `Map`
> > and `Set` (which are still `typeof f === "function"`).
> >
> > ```js
> > var funcToString = Function.prototype.toString
> >
> > function isCallable(f) {
> >    return typeof f === "function" &&
> >        /^\s*class(\s*\{|\s+[^(])/.test(funcToString.call(f))
> > }
> > ```
>
> Your `isCallable` function has a flaw: it will treat differently:
>
> ```js
> // ES6 class
> class Foo {
>     constructor() {
>         // ...
>     }
> }
> ```
>
> and:
>
> ```js
> // pre-ES6 almost-compatible approximation of a class
> function Foo() {
>     if (!(this instanceof Foo))
>         throw new TypeError("Foo must be invoked with 'new'");
>     // ...
> }
> ```
>
> You are unable to guess that a function defined with the `function`
> keyword is intended to be a constructor or a function.
>
> —Claude
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.mozilla.org/pipermail/es-discuss/attachments/20170124/148d9e05/attachment.html>


More information about the es-discuss mailing list