在 JavaScript 中将类实例作为函数调用

int*_*ion 8 javascript ecmascript-6

假设我有课

class foo {
  constructor() {
    this._pos = 0;
  }
  
  bar(arg) {
    console.log(arg);
  }
}

const obj = new foo();
Run Code Online (Sandbox Code Playgroud)

我如何才能调用:

let var1 = obj('something');
Run Code Online (Sandbox Code Playgroud)

小智 7

您可以通过扩展构造函数来创建可调用对象Function,但如果您希望它访问创建的实例,则实际上需要在构造函数中创建一个绑定函数,将实例绑定到返回的函数。

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 ');
Run Code Online (Sandbox Code Playgroud)