I'm a little bit confused with the class feature in es2016, though it is assumed to be just a syntax sugar for creating classes, in comparison to function and prototype, but the behaviour in some cases is different, in particular - classes can't be called same as functions and it seems, there is no way to find out if a function is the class constructor or a simple function, without using toString and the /^class/ RegExp.
Assume the example:
class Foo {
constructor () {
this.name = 'foo';
}
}
function Bar () {
this.name = 'bar';
}
function doSmth (anyArg) {
if (typeof anyArg === 'function') {
var obj = { someProp: 'qux' };
anyArg.call(obj);
return obj;
}
// ...
}
doSmth(Bar);
doSmth(Foo); // Class constructor Foo cannot be invoked without 'new'
Is typeof 'function', but can't call it as a function! Nice.
And here are my 2 questions:
- Is there some way I can call the
Fooconstructor function same asBarwith the overridenthiscontext? - Is there some way I can detect the
anyArgis the constructor of a class, sothat I can handle it differently in mydoSmthfunction. WithouttoStringand theRegExp(as the performance penalty would be huge in this case). I could then useReflect.constructto initialize the new instance, andObject.assignto extend myobjvariable with the values from the instance.
Thank you, Alex