Javascript: 像函数一样调用对象

Javascript: invoking objects like functions

我可以有一个创建实例的构造函数,但在调用时执行特定函数吗?

var Foo = function(){
    this.bar= "some variable";

   this.invokeFunction = function(){
        return this.bar;
    }
    return .... // what to do here
};

var foo = new Foo();

return foo;       // return the instance of Foo:  { bar: "some variable" }
return foo.bar; // returns "some variable"
return foo() ;    // returns "some variable"

在您的 class 函数中,return 一个 return 您想要的函数。所以像这样:

var Foo = function(){
    this.bar= "some variable";

   this.invokeFunction = function(){
        return this.bar;
    }
    return this.invokeFunction.bind(this);
}; 

你可以用这样的东西来伪造它。 Foo returns 一个函数,它有一个 __proto__ 指向它自己的原型。返回的函数是可调用的,是 Foo 的实例并且可以访问实例属性:

var Foo = function(){
    function inner(){
        console.log("called")
        return "returned"
    }

    inner.__proto__ = Foo.prototype
    inner.bar= "some variable";
    return inner
};

Foo.prototype.someFn = function(){
    console.log("called prototype function")
    return this.bar
}

var foo = new Foo();

console.log(foo instanceof Foo) // it's an instance of Foo
console.log(foo.bar) // still has access to instance variables
console.log(foo())  // callable!
console.log(foo.someFn()) // prototype function with `this`