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
Foo
constructor function same asBar
with the overridenthis
context? - Is there some way I can detect the
anyArg
is the constructor of a class, sothat I can handle it differently in mydoSmth
function. WithouttoString
and theRegExp
(as the performance penalty would be huge in this case). I could then useReflect.construct
to initialize the new instance, andObject.assign
to extend myobj
variable with the values from the instance.
Thank you, Alex