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)?

Answers:

Answer

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!

Answer

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:

Answer

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?)

Answer

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.

Tags

Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us Javascript

©2020 All rights reserved.