Tuesday, 15 June 2010

coding style - Is there anything wrong with this pattern for a JS library? -



coding style - Is there anything wrong with this pattern for a JS library? -

i admittedly know little inner workings of javascript, need create library , larn (hence asking here). understand using closure , exporting window not pollute global namespace, beyond confuses me bit.

(function() { var drop = window.drop = function() { var files = []; var add together = function(word) { files.push(word); homecoming files; } homecoming { files: files, add: add together } } })() // of these seem same? var = drop(); var b = new drop(); var c = new drop; // each has own state want. a.add("file1"); b.add("file2"); c.add("file3"); why 3 ways of "initializing" drop same? what gives them ability have own state? is there alternative homecoming syntax export functions on drop? is there flat out improve best practice way of creating self contained library this?

i have searched around net, have found little consistency on subject.

the first way (drop()) calls function normal, this global object (window in browser environments). stuff , returns object, you'd expect.

the sec way (new drop()) creates new drop object , executes constructor this set object. not, however, utilize this anywhere , homecoming object created object literal, drop object discarded , object literal returned instead.

the 3rd way (new drop) semantically same second; syntactic difference.

they have own state because each time phone call drop, has own set of local variables distinct local variables of other phone call drop.

you transform code utilize normal new syntax , prototypes. has few advantages: namely, create add function 1 time rather 1 each drop call. modified code might this:

function drop() { this.files = []; } drop.prototype.add = function(word) { this.files.push(word); homecoming this.files; };

by doing this, though, lose beingness able phone call without new. there is, however, workaround: can add together first line within function drop:

if(!(this instanceof drop)) { homecoming new drop(); }

since when phone call new, this drop, , when phone call without new, this other drop, can see if this drop, , if is, go on initializing; otherwise, reinvoke new.

there semantic difference. consider next code:

var drop = new drop(); var adder = drop.add; adder(somefile);

your code work here. prototype-based code not, since this global object, not drop. this, too, has workaround: somewhere in constructor, can this:

this.add = this.add.bind(this);

of course, if library's consumers not going pull function out of object, won't need this. furthermore, might need shim function.prototype.bind browsers don't have it.

no. it's matter of taste.

coding-style javascript

No comments:

Post a Comment