Javacript : Immediately invoking function expression

Author:Kostas Sp Published On:September 19, 2014 Under:Javascript

 
 

This is an first attemp to understand JAVASCRIPT fundamentals like self executing anonymus function. It is the MODULE PATTERN and we might also see it to some backbone applications

 

Also known as the self executing anonymus function and often in backbone all the code is wrapped inside a function expression that is self executed when the page loads

 

The reason we do this is because in Javascript doesn’t support the concept of private and public variables and methods

 

So to solve this issue Javascript uses closures. Which encapsulates all variables and methods inside a closure.

 

When you invoke this it creates a context and holds all variables and functions inside of that and it creates privacy

 

var app = (function($) {
 
alert("first shorthand function");
(function() {
    var foo = "bar";
}) ();

So if I try to output the variable for foo and see the value it would’t show to me

 

In order to show this to me I have created a function inside of that anonymus function I created a variable called foo that is equal to bar and then I immediatelly called that function

 

myFunction = function() {
    var foo = "bar";
    return foo; 
}

 

Why pass jQuery jQuery object will be accesible in the backbone application inside this function So I pass the jquery object and I assign it to the $ sign

 

If you want to test it in the console browser the command is

 

console.log(myFunction());
(function() {
    var foo = $('div');
}) (jQuery);

 

This leads to Module Pattern which was popularized by Duglas ClockWard I am assigning the return value of this anonymus function to a variable called app

 

So we wrap entire function inside these parantheses that way it tells that we are NOT assigning the variable app to the function BUT we setting the variable app equal to what is being returned from the function

 

var app = (function($) {
 
    var foo = "bar";
 
    return {
        name: "module pattern",
        set: function (name) {
            foo = name;
 
        },
        get: function () {
            return foo;
        }
 
    };
}) (jQuery);

 

Let’s check some command lines

 

// undefined because it is private

console.log(app.foo);

// module pattern

console.log(app.name);

// bar

console.log(app.get());

// undefined (no return) just sets

console.log(app.set("StackMob"));

// Stackmob
console.log(app.get());

   
Tags:
 

One response to “Javacript : Immediately invoking function expression”

  1. Kerry Dette says:

    Could you explain the Jquery part ?

Leave a Reply

Current day month [email protected] *


five − 1 =

.
 
Categories
TEST

Anything in here will be replaced on browsers that support the canvas element

Tags