javascript - Why doesn't this method call work from within a prototype? -
i'm trying larn how write improve javascript i'm not sure why doesn't work. have 2 method calls write text field. first 1 works fine, sec 1 doesn't. why text field variable undefined going thorough nested call? help appreciated:
(function () { var testobj = function (logel) { this.log = logel; }; testobj.prototype = function () { var log1 = function (text) { this.log.val(text); }; var log2 = function (text) { log1(text); } homecoming { log1: log1, log2: log2 }; }(); $(function () { var logel = $("#log"); var test = new testobj(logel); test.log1("this works"); test.log2("this dosen't"); //this.log undefined }); })()
as dc5 , hayes pointed out value of this
invoking object. it's object comes before function:
somebutton.click();//this somebutton click();//nothing before click, window assumed or throw exception in strict mode myobject.dosomething();//this in dosomething myobject
since log1 available through closures doesn't throw exception (log1 undefined) this
in log1 function window since log2 didn't provide invoking object.
to set invoking object alter code to:
log1.call(this,text);
i'm not big fan of throwing including kitchen sink in iife creates unneeded closures every method. can wrap application an object literal instead , utilize iife need closures:
var app ={ testobj:function(...
log1 won't available through closures in log2 can phone call using this
this.log1(text);
more on prototype, constructor functions, inheritance , value of this
can found here.
javascript
No comments:
Post a Comment