8

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');
8
  • 3
    You can't "call" a plain object; what would that even mean? What code would run? Commented Mar 14, 2018 at 14:02
  • Do you want to call bar method of foo class or what? Please clarify. 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. Commented Mar 14, 2018 at 14:03
  • 3
    meta.stackexchange.com/questions/66377/what-is-the-xy-problem Commented Mar 14, 2018 at 14:04
  • 1
    Technically you could extend built-in Function constructor using class Foo extends Function. Demo But you can doesn't mean you should. :) Commented Mar 14, 2018 at 14:09

1 Answer 1

9

You 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 ');

Sign up to request clarification or add additional context in comments.

1 Comment

A very elegant solution! Thank you!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.