Skip to content

Instantly share code, notes, and snippets.

@wentout
Last active September 1, 2020 18:56
Show Gist options
  • Save wentout/c49ef59413468d4f4910c81716960c75 to your computer and use it in GitHub Desktop.
Save wentout/c49ef59413468d4f4910c81716960c75 to your computer and use it in GitHub Desktop.
an example of instance as a callable function
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;
}
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