Calling class instance as a function in JavaScript

intellion Source

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');
javascriptecmascript-6

Answers

answered 3 months ago user9366559 #1

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

comments powered by Disqus