javascript - How to recognize the function is the class constructor and how to call it as a function? -
i'm little bit confused class feature in es2016, though assumed syntax sugar creating classes, in comparison function , prototype, behaviour in cases different, in particular - classes can't called same functions , seems, there no way find out if function class constructor or simple function, without using tostring , /^class/ regexp.
assume 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 invoked without 'new' is typeof 'function', can't call function! nice.
and here 2 questions:
- is there way can call
fooconstructor function samebaroverridenthiscontext? - is there way can detect
anyargconstructor of class, sothat can handle differently indosmthfunction. withouttostring,regexp(as performance penalty huge in case). usereflect.constructinitialize new instance, ,object.assignextendobjvariable values instance.
thank you, alex
no both questions.
here's how angular 1.x detects classes:
function isclass(func) { // ie 9-11 not support classes , ie9 leaks code below. if (msie <= 11 || typeof func !== 'function') { return false; } var result = func.$$ngisclass; if (!isboolean(result)) { // support: edge 12-13 // see: https://developer.microsoft.com/en-us/microsoft-edge/platform/issues/6156135/ result = func.$$ngisclass = /^(?:class\b|constructor\()/.test(stringifyfn(func)); } return result; } unfortunately, it's best possible solution. , doesn't work in firefox @ that.
Comments
Post a Comment