javascript - Breaking out a closure to explain it to the unitiated -
i've got this, , works:
myobject.myfunction = (function() { var closure = 0; return function(value) { if (arguments.length) { closure = value; } else { return closure; } } })(); it acts both getter , setter, calling myfunction(3.14) set closure , calling myfunction() closure's value.
q: can separate out more wordy example (without being ridiculous)? i'd this:
myobject.myfunction1 = myfunction2; myobject.myfunction1(); function myfunction2() { var closure = 0; return function(value) { if (arguments.length) { closure = value; } else { return closure; } } } i'm trying break down javascript small chunks possible students can concentrate.
edit 1:
oh wait: don't need myfunction2 @ all.
are looking simplest way explain closures like:
function closure() { var privatedata = "i'm hidden!"; return { get: function () { return privatedata; }, set: function (arg) { privatedata = arg; } }; } var privatedataaccess = closure(); console.log(typeof (privatedata)); // logs undefined -- privatedata out of scope console.log(privatedataaccess.get()); // logs "i'm hidden!" privatedataaccess.set("now changed me!"); console.log(privatedataaccess.get()); // logs "now changed me!" that simple gets think :-)
Comments
Post a Comment