Question

Say I have this module and I want it to self initialize and attach to its scope. Like so:

(function( scope ) {
    var Module = (function() {
      return {
          init: function(){
              console.log('Initialized');
          }
      };
    })();
    var module = scope.Module = Module;
    module.init();
})( self );

Now, the problem is, is that self is always the window. I don't want that. I want it to be the scope of where it's been invoked and loaded by jQuery's $.getScript(), like so:

var Master = (function($) {
    return {
        init: function() { 
            var self = this;
            $.getScript("/js/libs/module.js");
        }
    }
})(jQuery)

Is there a way to crack this?

Was it helpful?

Solution

I don't think you can inject scope to a self-executing script called with $.getScript. Instead you have to use some kind of exports variable to store the script until the scope can be injected.

(function( exports ) {
   exports.Module = function() {
     return {
        init: function(scope){
           console.log('Initialized', scope);
        }
     };
   };
   var module = exports.Module;
})( exports || window.exports = {} );

Then:

var self = this; // or whatever you want the scope to be
$.getScript("/js/libs/module.js", function(){
    exports.Module().init(self);
});

Honestly, if you are using jQuery for the module pattern like this, consider using a more comprehensive library loader such as require.js or Frame.js.

OTHER TIPS

Scope in JavaScript is closely tied to functions, not objects. An object in JS {} does not create it's own scope. I'm not familiar with the "Revealing Module Pattern" in jQuery, but to get a unique scope you would do something like this:

(function( scope ) {
    var Module = (function() {
      return new function() {
          this.init = function(){
              console.log('Initialized');
          }
      };
    })();

    var module = scope.Module = Module;
    module.init();

})();

Or, perhaps more tersely:

(function( scope ) {
    var Module = new function() {
        this.init = function(){
          console.log('Initialized');
        };
    };

    var module = scope.Module = Module;
    module.init();

})();

In this case, the scope is Module, not window.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top