jQuery function declaration explanation

前端 未结 4 1957
-上瘾入骨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:51

    This is because it is within an object. Object Literals have their properties defined in this way:

    {
        name: value,
        //OR
        'name': value
    }
    

    Where value can be nearly anything such as a number, string, function, or even another object. In JavaScript you can also declare anonymous functions and assign them to a variable. In fact, the following declarations have the same effect:

    //declares the myFunc1 function
    function myFunc1() {}
    //declares an anonymous function and assigns it to myFunc2
    var myFunc2 = function() {};
    
    //you can now call either like so:
    myFunc1();
    myFunc2();
    

    So, combining those two concepts if I have an object and I want one of its properties to be a function I would do it like so:

    var myObj = {
        name: 'My Object',
        init: function() {
            return 'Initializing!';
        },
        version: 1.0
    };
    
    alert(myObj.init());
    

    You would then get the output: Initializing!. Make sure to check out the great documentation and tutorials on the Mozilla Developer Network, including their JavaScript Tutorial Series

    Hope this helps!

提交回复
热议问题