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. C++ async task

    最近在搞Android 开发,里面多线程的使用比较频繁,java多线程接口很方便. Thread, AysncTask, Handler 这些接口比起posix提供的pthread_create()等 ...

  2. "浅谈Android"第一篇:Android系统简介

    近来,看了一本书,名字叫做<第一行代码>,是CSDN一名博主写的,一本Android入门级的书,比较适合新手.看了书之后,有感而发,想来进行Android开发已经有一年多了,但欠缺系统化的 ...

  3. android resources使用总结

    http://developer.android.com/guide/topics/resources/more-resources.html http://developer.android.com ...

  4. 第九篇 SQL Server代理了解作业和安全

    本篇文章是SQL Server代理系列的第九篇,详细内容请参考原文 在这一系列的上一篇,学习了如何在SQL Server代理作业步骤启动外部程序.你可以使用过时的ActiveX系统,运行批处理命令脚本 ...

  5. python+selenium+unittest,爬虫电影网站

    以前经常在这个网站上下载电影下来看,这个网站比较坑的就是,主页上只有电影的名称,但是评分是看不到的:只有再点击电影名字,进入电影主页时才能看到评分.一般下载的电影都是评分高的才看,低的就忽略掉了.每次 ...

  6. maven异常解决:编码GBK的不可映射字符

    直接将项目改为UTF-8编码,无效!要通过修改pom.xml文件,告诉maven这个项目使用UTF-8来编译. 一.问题描述 今天在MyEclipse中使用Maven编译项目源代码时,结果如下了如下的 ...

  7. MVC。Action方法,常用的返回类型有几种?

    常用的: 1,string,直接返回响应报文字符串 public ActionResult test(){return "哈哈";}2.ViewResult,ActionResul ...

  8. C#属性封装

    1.属性封装是为了保护与之相对应的字段的,保证字段的读取和赋值是否符合要求 2.属性可以分为:读写,只读,只写 3.允许外部访问的变量一定要申明为属性 4.属性的本质就是两个方法. 5.自动属性 6. ...

  9. 根据Expander的IsExpanded属性值的变化动态设计Control的size

    简要说明: 当Expander 的IsExpanded属性为“True” 时给控件设个尺寸(此处为高度),当为“False”时给控件设另外一个值. 知识点:数据绑定.Style和Trigger < ...

  10. 【JS复习笔记】06 方法

    数组的方法: array.concat   一个数组去连接另一个数组,返回一个合成数组.var arrC=arrA.concat(arrB,'asd','sad',true,1.5); array.j ...