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?

fiddle: https://jsfiddle.net/bloodbaz/zz11n5wp/1/

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(); 

https://jsfiddle.net/zz11n5wp/2/


Comments

Popular posts from this blog

Magento/PHP - Get phones on all members in a customer group -

php - .htaccess mod_rewrite for dynamic url which has domain names -

Website Login Issue developed in magento -