Assuming I have a class
class foo {
constructor() {
this._pos = 0;
}
bar(arg) {
console.log(arg);
}
}
const obj = new foo();
Assuming I have a class
class foo {
constructor() {
this._pos = 0;
}
bar(arg) {
console.log(arg);
}
}
const obj = new foo();
How do I make it possible to call:
let var1 = obj('something');
Share
Improve this question
asked Mar 14, 2018 at 13:59
intellionintellion
1,43713 silver badges27 bronze badges
8
- 3 You can't "call" a plain object; what would that even mean? What code would run? – Pointy Commented Mar 14, 2018 at 14:02
-
Do you want to call
bar
method offoo
class or what? Please clarify. – standby954 Commented Mar 14, 2018 at 14:02 - What you have and what you want to do don't go with each other. You have an instance of a class (an object) and you want to invoke the object as a function. – Scott Marcus Commented Mar 14, 2018 at 14:03
- 3 meta.stackexchange./questions/66377/what-is-the-xy-problem – Yury Tarabanko Commented Mar 14, 2018 at 14:04
-
1
Technically you could extend built-in
Function
constructor usingclass Foo extends Function
. Demo But you can doesn't mean you should. :) – Yury Tarabanko Commented Mar 14, 2018 at 14:09
1 Answer
Reset to default 9You can make a callable object by extending the Function
constructor, though if you want it to access the instance created, you'll actually need to create a bound function in the constructor that binds the instance to a function that is returned.
class foo extends Function {
constructor() {
super("...args", "return this.bar(...args)");
this._pos = 0;
return this.bind(this);
}
bar(arg) {
console.log(arg + this._pos);
}
}
const obj = new foo();
let var1 = obj('something ');