Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 code here
},

I learned to define function on this way:

function show() {
  //some code here
}

Can someone explain me why show function is not written on second way (like in most tutorials on internet)?

like image 486
Иван Бишевац Avatar asked Jun 29 '26 03:06

Иван Бишевац


2 Answers

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!

like image 107
Chad Avatar answered Jul 01 '26 17:07

Chad


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/
like image 32
swatkins Avatar answered Jul 01 '26 15:07

swatkins