Determine if a value is Callable/Constructible

Peter Flannery flannery.peter at ntlworld.com
Mon Mar 30 11:09:20 UTC 2015


>> On Mar 30, 2015, at 10:12 AM, Axel Rauschmayer <axel at rauschma.de>
wrote:
>>
>>>> It doesn’t seem that big of a deal, but one risk is: people mistaking
a class for a constructor, trying to subclass it as if it were a
constructor and things failing silently.
>>>>
>>> Can you give an example of what you mean?
>>
>> ```js
>> class MySuperClass {}
>>
>> // This function assumes that MySuperClass is an ES5 constructor function
>> function MySubConstructor(foo) {
>>    MySuperClass.call(this);
>>    this.foo = foo;
>> }
>> MySubConstructor.prototype = Object.create(MySuperClass.prototype);
>> MySubConstructor.prototype.constructor = MySubConstructor;
>> ```
>
> so if MySuperCall didn’t have the throw on [[Call]] behavior the above
would work just fine.
>
> Allen

Would this be a work around? i'm seeing this work with v8 harmony classes
enabled, or is this something that wont work eventually?
```js
function MySubConstructor(foo) {
  MySuperClass.constructor.call(this)
  this.foo = foo;
}
```

I also noticed that using apply to chain constructors won't work either as
currently mentioned at Mozilla [Using apply to chain constructors](
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/apply#Example:_Using_apply_to_chain_constructors
)

```js
//
function applyConstructor(ctor, args) {
    var child = Object.create(ctor.prototype);
    var result = ctor.apply(child, args); // !!! throws Class constructors
cannot be invoked without 'new'
    return result && Object(result) === result ? result : child;
}
```

but this still seems to work
```js
function applyConstructor(ctor, args) {
    return new (Function.prototype.bind.apply(ctor, [null].concat(args)));

}
```
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.mozilla.org/pipermail/es-discuss/attachments/20150330/78c5e8a3/attachment.html>


More information about the es-discuss mailing list