在Node.JS的类中处理函数调用

假设你有一堂课

class MyClass { world() { console.log("hello world"); } } 

我可以运行类似于以下的方法:

 var hello = new MyClass(); hello.world(); # outputs: hello world 

有没有办法处理对象的直接函数调用? 例如:

 hello(); 

返回: TypeError: hello is not a function

我可以将此通话设为默认function吗? 例如,类似于PHP的invoke函数 …

我们只能在JavaScript中调用可以调用的东西,如果这个东西是一个对象,在某些情况下,这个对象委托给Function.prototype 。 所以,我们的类需要extend Function或者extend一个extend s Function的类。 我们还需要能够从我们的类对象(为了调用invoke() )访问实例variables,所以它需要绑定到它自己。 这个绑定只能在构造函数中发生。

由于我们的类将inheritance自Function ,因此我们需要调用super来使用this 。 然而, Function构造函数实际上需要一个代码string,我们不会有,因为我们希望能够稍后设置invoke 。 所以我们需要在一个不同的类中extend Function ,这个类将是我们类的父类,它将完成我们虚拟函数的原型设置(为了能够调用返回的对象) 。 把所有这些结合在一起,我们得到:

 class ExtensibleFunction extends Function { constructor(f) { // our link to Function is what makes this callable, // however, we want to be able to access the methods from our class // so we need to set the prototype to our class's prototype. return Object.setPrototypeOf(f, new.target.prototype); } } class MyClass extends ExtensibleFunction { constructor() { // we build an ExtensibleFunction which accesses // the late-bound invoke method super(function() { return this.invoke(); }); return this.bind(this); // and bind our instance // so we have access to instance values. } invoke() { console.log("Hello, world!"); } } x = new MyClass(); x(); //prints "Hello, world!"