The immediate function pattern is a syntax that enables you to execute a function as soon as it is defined.

(function () {

    alert('watch out!');

}()); 

• You define a function using a function expression. (A function declaration won’t work.)

• You add a set of parentheses at the end, which causes the function to be executed immediately.

• You wrap the whole function in parentheses (required only if you don’t assign the function to a variable).

(function () {

    var days = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'],

         today = new Date(),

         msg = 'Today is ' + days[today.getDay()] + ', ' + today.getDate();

    alert(msg);

}()); // "Today is Fri, 13"

If  this  code  weren’t  wrapped  in  an  immediate  function,  then  the  variables  days, today, and msg would all be global variables, leftovers from the initialization code.

Parameters of an Immediate Function

// prints:

// I met Joe Black on Fri Aug 13 2010 23:26:59 GMT-0800 (PST)

(function (who, when) {

    console.log("I met " + who + " on " + when);

}("Joe Black", new Date())); 

Commonly, the global object is passed as an argument to the immediate function so that it’s accessible inside of the function without having to use window.

(function (global) {

    // access the global object via `global`

}(this)); 

Shouldn’t pass too many parameters to an immediate function, because it could quickly become a burden to constantly scroll to the top and to the bottom of the function to understand how it works.

Returned Values from Immediate Functions

var result = (function () {

    return 2 + 2;

}()); 

use the scope of the immediate function to privately store some data, specific to the inner function you return.

var getResult = (function () {

    var res = 2 + 2;

    return function () {

        return res;

    };

}()); 

Used for Defining object properties

var o = {

    message: (function () {

        var who = "me",

            what = "call";

        return what + " " + who;

    }()),

    getMsg: function () {

        return this.message;

    }

};

// usage

o.getMsg(); // "call me"

o.message; // "call me" 

Benefits and Usage

It helps you wrap an amount of work you want to do without leaving any global variables behind. All the variables you define will be local to the self-invoking functions and you don’t have to worry about polluting the global space with temporary variables.

Enables you to wrap individual features into self-contained modules.

// module1 defined in module1.js

(function () {

    // all the module 1 code ...

}());

JavaScript Patterns 4.5 Immediate Functions的更多相关文章

  1. JavaScript Patterns 4.4 Self-Defining Functions

    If you create a new function and assign it to the same variable that already holds another function, ...

  2. JavaScript Patterns 4.3 Returning Functions

    Use closure to store some private data, which is accessible by the returned function but not to the ...

  3. JavaScript Patterns 7.1 Singleton

    7.1 Singleton The idea of the singleton pattern is to have only one instance of a specific class. Th ...

  4. JavaScript Patterns 6.5 Inheritance by Copying Properties

    Shallow copy pattern function extend(parent, child) { var i; child = child || {}; for (i in parent) ...

  5. JavaScript Patterns 5.8 Chaining Pattern

    Chaining Pattern - Call methods on an object one after the other without assigning the return values ...

  6. JavaScript Patterns 5.5 Sandbox Pattern

    Drawbacks of the namespacing pattern • Reliance on a single global variable to be the application’s ...

  7. JavaScript Patterns 5.3 Private Properties and Methods

    All object members are public in JavaScript. var myobj = { myprop : 1, getProp : function() { return ...

  8. JavaScript Patterns 4.10 Curry

    Function Application apply() takes two parameters: the first one is an object to bind to this inside ...

  9. JavaScript Patterns 6.7 Borrowing Methods

    Scenario You want to use just the methods you like, without inheriting all the other methods that yo ...

随机推荐

  1. [Python] raw_input

    该函数输入的是字符串,如果想输入数字,可以用强制转换.

  2. SQL 分类统计函数

    SELECT TransactionNumber,SUM(CASE WHEN ReasonLevel=0 THEN           TransactionNumber ELSE 0 end ) a ...

  3. BZOJ1008 /乘法原理+快速幂 解题报告

    1008: [HNOI2008]越狱 Description 监狱有连续编号为1...N的N个房间,每个房间关押一个犯人,有M种宗教,每个犯人可能信仰其中一种.如果相邻房间的犯人的宗教相同,就可能发生 ...

  4. Sql Server来龙去脉系列之三 查询过程跟踪

    我们在读写数据库文件时,当文件被读.写或者出现错误时,这些过程活动都会触发一些运行时事件.从一个用户角度来看,有些时候会关注这些事件,特别是我们调试.审核.服务维护.例如,当数据库错误出现.列数据被更 ...

  5. oracle的minus返回第一个表中有、第二个表中没有的数据

    oracle的minus返回第一个表中有.第二个表中没有的数据 CREATE TABLE hovertree_union_1 ( id INT, val ) ); CREATE TABLE hover ...

  6. easyui-简单用法寄一些属性

    Easyui 总结 优点: A.简单易用 继承 jQuery 简易使用特性,提供高度抽象接口,短期改善网站易用性. B.开源免费 采用 MIT & GPL 双协议授权,轻松满足自由产品至企业产 ...

  7. bootstrap - table

    http://bootstrap-table.wenzhixin.net.cn/zh-cn/documentation/

  8. 重新想象 Windows 8 Store Apps 系列文章索引

    [源码下载][重新想象 Windows 8.1 Store Apps 系列文章] 重新想象 Windows 8 Store Apps 系列文章索引 作者:webabcd 1.重新想象 Windows ...

  9. ati显卡驱动后,性能不咋地

    ubuntu装了ati的闭源驱动后,拖动窗口,会有明显的断裂感,不够平滑

  10. jQuery使用ajaxStart()和ajaxStop()方法

    ajaxStart()和ajaxStop()方法是绑定Ajax事件.ajaxStart()方法用于在Ajax请求发出前触发函数,ajaxStop()方法用于在Ajax请求完成后触发函数.它们的调用格式 ...