我可以有一个构造函数来创建一个实例,但是在调用时会执行一个特定的函数吗?
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"
答案 0 :(得分:1)
你可以用这样的东西伪造它。 Foo返回一个函数,其__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`
答案 1 :(得分:0)
在类函数中,返回一个返回所需内容的函数。所以像这样:
var Foo = function(){
this.bar= "some variable";
this.invokeFunction = function(){
return this.bar;
}
return this.invokeFunction.bind(this);
};