www.webdeveloper.com
Results 1 to 4 of 4

Thread: Javascript Namespacing Question

  1. #1
    Join Date
    Mar 2014
    Posts
    8

    Javascript Namespacing Question

    Hi
    Well study the javascript namespacing I know the self-executing anonymous function
    (function(){
    // Code here
    })();

    but I have a question, is about jquery, they send window like argument?
    (function(window){
    // Code here
    window.example = example;
    })(window);
    wich are the diference to use window inside the function without send this like argument?
    (function(){
    // Code here
    window.example = example;
    })();
    Thanks.

  2. #2
    Join Date
    Mar 2014
    Location
    London
    Posts
    20
    When you write a function like:
    PHP Code:
    (function (example) {
            
    reutrn exa.getElementById(mple);
    })(
    window"myElement"
    then this function is called with arguements "window" and "myElement" for parameters "exa" and "mple". Therefore, inside the function exa.getElementById(mple) is equivalent to window.getElementById("myElement")
    You don't need to include these. Assigning function-local variables to reference these will just take less time to resolve these variables. Unless you have used a lot of references to window, my advice is - don't bother.

  3. #3
    Join Date
    Mar 2005
    Location
    Sydney, Australia
    Posts
    7,974
    [QUOTE=aixeiger;1319717but I have a question, is about jquery, they send window like argument?
    (function(window){
    // Code here
    window.example = example;
    })(window);
    wich are the diference to use window inside the function without send this like argument?
    (function(){
    // Code here
    window.example = example;
    })();
    Thanks.[/QUOTE]

    A simple jQuery example:

    Code:
    jQuery.noConflict();
    (function($) {
       "use strict";
       var i, j; // declare all variables here
       
       // code goes here
       
    })(jQuery);
    With this code you can now use $ to refer to the jQuery library inside the function while using $ for a different library (eg. prototype) elsewhere in your code.

    Passing a variable into the function like that makes a local copy of that value that can be used independently of anything outside of the function - in this case being able to use $ to reference jQuery from inside the function while specifically releasing that variable for other use outside of the function.
    Stephen

  4. #4
    Join Date
    Mar 2014
    Posts
    8
    Thank felgall, this make me have a more accurate idea to how works an anonymous self-invocation functions!

Thread Information

Users Browsing this Thread

There are currently 1 users browsing this thread. (0 members and 1 guests)

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  
HTML5 Development Center



Recent Articles