Determining if an object can be constructed

Claude Pache claude.pache at gmail.com
Tue Jan 17 13:31:36 UTC 2017


> Le 16 janv. 2017 à 18:00, Michael Haufe <tno at thenewobjective.com> a écrit :
> 
> The question came up recently on CLJS [1] on how to determine if an object is safe to call as a Constructor.

The two following procedures will determine whether an object is a constructor without running it, according to ES6. (Whether it is safe to call it as constructor... you need first a definition of "safe".)

(1) Using `class/extends`:

```js
function isConstructor1(f) {
    if (f === null)
        return false
    try {
        class c extends f { }
        return true
    }
    catch (e) {
       return false
    }
}
```

(2) Using `Proxy`:

```js
function isConstructor2(f) {
    var p = new Proxy(f, { construct() { return {} } })
    try {
        new p
        return true
    }
    catch (e) {
       return false
    }
}
```


—Claude



More information about the es-discuss mailing list