Last active
September 1, 2020 18:56
-
-
Save wentout/c49ef59413468d4f4910c81716960c75 to your computer and use it in GitHub Desktop.
an example of instance as a callable function
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class MyClass {} | |
class FunctionAsInstance extends MyClass { | |
constructor(...args) { | |
super(); | |
const me = this; | |
this.args = args; | |
const callable = function (_args) { | |
me._args = _args; | |
return me; | |
}; | |
Reflect.setPrototypeOf(callable, me); | |
return callable; | |
} | |
} | |
const me = new FunctionAsInstance(123); | |
try { | |
const result = me(123); | |
console.log(result instanceof FunctionAsInstance); | |
console.log(result instanceof MyClass); | |
console.log(result.args); | |
console.log(result._args); | |
} catch (e) { | |
debugger; | |
} | |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class MyClass {} | |
class FunctionAsInstance extends MyClass { | |
constructor() { | |
super(); | |
const me = this; | |
const callable = function () { | |
return me; | |
}; | |
callable.prototype = me; | |
callable.prototype.constructor = FunctionAsInstance; | |
return new Proxy(callable, { | |
get (target, prop) { | |
return Reflect.get(me, prop) | |
}, | |
set (target, prop, value) { | |
Reflect.set(me, prop, value) | |
} | |
}); | |
} | |
} | |
const me = new FunctionAsInstance; | |
try { | |
const result = me(123); | |
console.log(result instanceof FunctionAsInstance); | |
console.log(result instanceof MyClass); | |
} catch (e) { | |
debugger; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment