jquery - $.each changes this context inside a module closure -
i have build standard javascript module (pattern) contains number of private methods , variables. finding fighting maintaining this
context point module after using $.each
.
i know jquery $.each
method creates closure , hence new "context", want continue have this
referring module. i've found calling module's private function (initfruit()
in sample) using initfruit.call() , passing in self
copy of this
(which "in scope") works for function, function calls another function, context lost again.
i don't want calling private functions .call() time because made use of $.each
further call stack how use $.each
without having original context lost?
in scope context define inner closures substitute this
(say: 90% of cases in private "methods"), easiest way have "global scope"'s this
element define variable, typically self
right in first line of main code block. in case "global" this
window
, here i'd do, in few words replacing "this" "self" when want reference object , this
when want reference inner closure:
var mymodule = (function ($) { var self = {}; var privatefunction = function () { console.log(self); } self.init = function () { privatefunction(); // exposes public methods of self, keeping "private" functions private }; return self; }(jquery)); mymodule.init();
Comments
Post a Comment