[英]JavaScript constructor whose instances are functions
I know this may be a bizarre question with possibly no practical application, but would it be possible to make a JavaScript class that constructs instances that behave as functions? 我知道这可能是一个奇怪的问题,可能没有实际应用,但是是否有可能制作一个JavaScript类来构造充当函数的实例? Here's what I mean: 这就是我的意思:
function Factory() {}
// this may not be necessary, but I'll include it for sake of clarification
Factory.prototype = Object.create(Function.prototype);
var method = new Factory();
method(); // Objective: should not throw TypeError
To further clarify the objective: 为了进一步阐明目标:
method
should be callable as a function method
应可作为函数调用 method
should be the result of calling a constructor (eg var method = new Factory()
in this case) method
应该是调用构造函数的结果(例如,在这种情况下, var method = new Factory()
) Function
. 构造Function
不能为Function
。 If I understand correctly. 如果我理解正确。 Object constructor need to return his method. 对象构造函数需要返回他的方法。 Then you can call it like you describe. 然后,您可以像描述的那样调用它。
function Factory() {
return this.method;
}
Factory.prototype.method = function() {
console.log('from method');
};
var method = new Factory();
method();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.