Skip to content Skip to sidebar Skip to footer

Jquery Function Declaration Explanation

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: function() { //some

Solution 1:

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 functionfunctionmyFunc1() {}
//declares an anonymous function and assigns it to myFunc2var 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!

Solution 2:

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

For example:

// I can create a new empty objectvar myObject = {};

// or I can create a new object with a basic propertyvar 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:

Solution 3:

The first declaration, i.e., show: function, defines show to be a field in an object having type function. The second declares a function named show within the current scope (possibly global?)

Solution 4:

they're being described as a js object function. In this case:

var jQuery = {
    show: function(){
        //some code here
    }
}

so you access it like jQuery.show() for example.

I would say Chad's answer is most accurate for in depth research. You should look into them as they can revolutionize how you write js in a very clean way that is much less likely to conflict with other libraries.

Post a Comment for "Jquery Function Declaration Explanation"