JavaScript中的函数是一等公民 - 但如何与new
结合使用?
我知道如何创建一个既像函数又像对象的对象。
fetch.proxy = '127.0.0.1'
fetch(url)
但是我正在尝试想出如何将此与创建一个new
实例相结合,以便我可以做类似于以下的操作:
a = new Fetch(host, username)
a(path1) // fetches username@host/path1
a(path2) // fetches username@host/path2
(只有一个实例的不太有用的示例)
以下方法不起作用,因为应用new
会返回一个对象(因此会得到TypeError:object is not a function
)。
var Fetch = function(a, b){
if ( (this instanceof arguments.callee) ){
//called as constructor
this.host = a
this.username = b;
this.host = 'localhost'
} else {
//called as function
console.log("Fetching "+this.username+'@'+this.host+a);
}
};
a = new Fetch('host', 'username')
a('/path1') // TypeError: object is not a function
a('/path2') // TypeError: object is not a function
我一直在研究基于
Fetch.prototype.constructor
的IT技术,并参考了http://tobyho.com/2010/11/22/javascript-constructors-and/和What it the significance of the Javascript constructor property?,但必须承认我开始质疑是否可能实现它。您有什么好的想法吗?