jQuery function declaration explanation

前端 未结 4 1965
-上瘾入骨i
-上瘾入骨i 2021-01-22 22:09

I\'ve opened jQuery 1.7.1 library and wanted to study the code, but I\'ve found a that functions are declared in strange way (for me). For example:

show: functio         


        
4条回答
  •  半阙折子戏
    2021-01-22 22:40

    Writing it the first way is in essence, setting a function as property of an object.

    For example:

    // I can create a new empty object
    var myObject = {};
    
    // or I can create a new object with a basic property
    var myObject = { 
            color: "blue" 
        };
    
    // I can also create an object with methods (like jQuery)
    var myObject = { 
            color: "blue", 
            showColor: function(){ 
                alert(this.color); 
            } 
        };
    
    // and you can use the object like this
    myObject.showColor(); // calls the showColor method and will alert "blue"
    

    This helps jQuery to encapsulate, namespace, and organize code.

    Here are a couple of pretty good write-ups:

    • Why do you need to invoke an anonymous function on the same line?
    • http://en.wikibooks.org/wiki/JavaScript/Anonymous_Functions
    • http://www.evotech.net/blog/2008/07/javascript-object-literals-a-definition/

提交回复
热议问题