Function are first class objects in JavaScript - but how to use that in combination with new
?
I get how to make an object that acts both like a function and like an object
fetch.proxy = '127.0.0.1'
fetch(url)
But I am trying to figure out how I can combine this with creating a new
intance so I can do something along the lines of:
a = new Fetch(host, username)
a(path1) // fetches username@host/path1
a(path2) // fetches username@host/path2
(not so useful example with only 1 instance)
The following approach does not work as applying new
returns an object (so get 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
I have been playing with Fetch.prototype.constructor
based on http://tobyho.com/2010/11/22/javascript-constructors-and/ and What it the significance of the Javascript constructor property? but must admit I have started to question if its possible at all.
Do you have any good ideas?