views:

52

answers:

1
+2  Q: 

jQuery initiation

Hi,

After using jQuery for a long time now I have a question, I'm writing a simple code using the jQuery pattern(style),

(function(window, undefined) {
     var jQuery = function (s, c) { ... }
}) (window);

As we all know jQuery is defined in a self Executing anonymous function, I guess its scope (jQuery) should be restricted to that anonymous function, but how do we have access to the jQuery outside the anonymous method ? If my assumption is wrong... Please Correct me.

I tried to write a code something similar to jQuery passion i.e., wrapping up my entire code in an anonymous method, like

(function( w, u ) {
  var JS = function() { return JS.fn.init();};

  JS.fn = JS.prototype = {
     init : function () {
         alert('Initiated');
         return this;
     }
  };

}) (window);

When I tried to call JS().init(); I'm getting an error in my firebug console saying that JS is not defined . Where I'm going wrong? Is it due to the scope limitation or poorly written code ?

+3  A: 

At the end, assign your object to window which makes it globally available even outside your anonymous function.

window.JS = JS;

Checkout this line in jQuery's source towards the very end which shows why jQuery and $ is defined even outside that anonymous function.

window.jQuery = window.$ = jQuery;

Besides scope, a few other things worth noting,

JS.init() does not exist because no new object is being created. Create a new object using the init constructor function.

var JS = function() { return new JS.fn.init(); };

By creating a new function when JS() is called, you don't need to call init yourselves anymore. To create new objects, simply use:

var foo = JS();

Here's the full source:

(function( w, u ) {
    var JS = function() { 
        // create a new object
        return new JS.fn.init();
    };

    JS.fn = JS.prototype = {
        init : function () {
            console.log('Initiated');
            return this; // not needed
        }
    };

    // link the init constructor with JS.prototype
    JS.fn.init.prototype = JS.fn;

    // make globally available
    window.JS = JS;

}) (window);
Anurag