javascript - New instance of function with object property -


function first class objects in javascript - how use in combination new?

i how make object acts both function , object

fetch.proxy = '127.0.0.1' fetch(url) 

but trying figure out how can combine creating new intance can along lines of:

a = new fetch(host, username)   a(path1) // fetches username@host/path1  a(path2) // fetches username@host/path2 

(not useful example 1 instance)

the following approach not work applying new returns object (so typeerror: object not function).

var fetch = function(a, b){      if ( (this instanceof arguments.callee) ){         //called constructor         this.host =         this.username = b;         this.host = 'localhost'      } else {     //called function    console.log("fetching "+this.username+'@'+this.host+a);     } };  = new fetch('host', 'username')   a('/path1') // typeerror: object not function  a('/path2') // typeerror: object not function 

i have been playing fetch.prototype.constructor based on http://tobyho.com/2010/11/22/javascript-constructors-and/ , what significance of javascript constructor property? must admit have started question if possible @ all.

do have ideas?

how use in combination new?

it doesn't make sense that. new foo create new object inherits foo.prototype. not possible have functions inherit prototype other function.prototype, there no advantage use new something create function.


since not using prototype in example, doesn't matter though. return function fetch:

var fetch = function(host, username){   function fetch(path) {      console.log("fetching " + fetch.username + '@' + fetch.host + path);   }   fetch.username = username;   fetch.host = host;   return fetch; }; 

now can call fetch or without new **, doesn't make difference:

var = fetch(host, username); // same var = new fetch(host, username); 

note changed this.username fetch.username in above example. every function has own this value does not refer function instance default, this.username not work.

this allow changing host or username after creation via a.username = 'something else';, etc. if don't want that, change fetch.username username.


**: if function explicitly returns object, new return value instead of newly created object inheriting fetch.prototype.


Comments

Popular posts from this blog

toolbar - How to add link to user registration inside toobar in admin joomla 3 custom component -

linux - disk space limitation when creating war file -

How to provide Authorization & Authentication using Asp.net, C#? -