Tuesday, 15 May 2012

javascript - Extending prototype within anonymous function - strange effects -



javascript - Extending prototype within anonymous function - strange effects -

when experimenting method create private static methods, came across unusual behavior. in next code, public method getdata overwritten it's own homecoming data, though never explicitly called! unusual me , wondered going on here. suppose serves me right not encompassing entire page in anonymous function per module pattern, still understand bug.

function myclass() { this._prop = true; } myclass.prototype.getdata = function () { this._prop = false; homecoming { a: 2344, b: 765, c: 234 }; } (function () { var privatestatic = 0; myclass.prototype.getcount = function () { homecoming privatestatic++; } } ()); var m = new myclass(); console.log(m.getdata()); //error (object not function) console.log(m.getdata); //prints {a:2344,b:765,c:234}

the reason unusual behavior getdata beingness invoked due lack of semicolon after function declaration (great spot, dandavis) , iife straight after it, wrapped in parens. essentially, this:

myclass.prototype.getdata = function () { this._prop = false; homecoming { a: 2344, b: 765, c: 234 }; } // notice no semicolon here! (function () { var privatestatic = 0; myclass.prototype.getcount = function () { homecoming privatestatic++; } } ());

becomes this:

myclass.prototype.getdata = function () { this._prop = false; homecoming { a: 2344, b: 765, c: 234 }; }();

which hence setting getdata property homecoming value of function. hence why m.getdata prints out { a: 2344, b: 765, c: 234 } , m.getdata() doesn't work (it's no longer function!).

javascript closures anonymous-function

No comments:

Post a Comment