Determining if an object can be constructed

Claude Pache claude.pache at gmail.com
Tue Jan 24 18:47:18 UTC 2017


> 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


More information about the es-discuss mailing list