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. 在eclipse中配置python插件

    最好离线下载python的离线包.名字叫——org.python.pydev.feature-1.6.3.2010100513 此包里面有两个文件夹 features 和 plugins,分别把2包中 ...

  2. 在SQL Server里如何进行页级别的恢复

    在今天的文章里我想谈下每个DBA应该知道的一个重要话题:在SQL Server里如何进行页级别还原操作.假设在SQL Server里你有一个损坏的页,你要从最近的数据库备份只还原有问题的页,而不是还原 ...

  3. How to remove replication in SyteLine V2

    以前曾经写了一篇<How to remove replication in Syteline>http://www.cnblogs.com/insus/archive/2011/12/20 ...

  4. AEAI ESB V3.5.4开源发布,应用集成平台

    AEAI ESB 应用集成平台为数通畅联的核心产品,本着分享传递的理念,数通畅联将ESB管理控制台项目开源,目的在于满足客户与伙伴的OEM需求,以及为广大IT爱好者的集成工具提供多一种选择,多一种便利 ...

  5. meta元素常用属性整理

    感谢菜鸟教程 参考资料:http://www.runoob.com/w3cnote/meta.html

  6. Can you explain Lazy Loading?

    Introduction Lazy loading is a concept where we delay the loading of the object until the point wher ...

  7. struts2进阶篇(4)

    一.使用ActionContext访问Servlet API strtus2提供了一个ActionContext类,该类别称为Action上下文或者Action环境,Action可以通过该类来访问最常 ...

  8. C语言范例学习03-上

    第三章 数据结构 章首:不好意思,这两天要帮家里做一些活儿.而且内容量与操作量也确实大幅提升了.所以写得很慢. 不过,从今天开始.我写的东西,许多都是之前没怎么学的了.所以速度会慢下来,同时写得也会详 ...

  9. 一个小笔记(7):EN_1

    For nearly ten years, the Unified Modeling Language(UML) has been the industry standard for visualiz ...

  10. NullPointerException at android.widget.AbsListView.obtainView at android.widget.ListView.makeAndAddView

    使用ExpandableListView的时候,报如下错.网上搜索发现原来是在CommonNumberQueryAdapter的getGroupView()方法里返回的是null,注意细节哦!!! 1 ...