JavaScript Patterns 4.5 Immediate Functions
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的更多相关文章
- 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, ...
- JavaScript Patterns 4.3 Returning Functions
Use closure to store some private data, which is accessible by the returned function but not to the ...
- 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 ...
- JavaScript Patterns 6.5 Inheritance by Copying Properties
Shallow copy pattern function extend(parent, child) { var i; child = child || {}; for (i in parent) ...
- JavaScript Patterns 5.8 Chaining Pattern
Chaining Pattern - Call methods on an object one after the other without assigning the return values ...
- JavaScript Patterns 5.5 Sandbox Pattern
Drawbacks of the namespacing pattern • Reliance on a single global variable to be the application’s ...
- JavaScript Patterns 5.3 Private Properties and Methods
All object members are public in JavaScript. var myobj = { myprop : 1, getProp : function() { return ...
- JavaScript Patterns 4.10 Curry
Function Application apply() takes two parameters: the first one is an object to bind to this inside ...
- JavaScript Patterns 6.7 Borrowing Methods
Scenario You want to use just the methods you like, without inheriting all the other methods that yo ...
随机推荐
- [linux]scp指令
实例1:从远处复制文件到本地目录 $scp root@10.6.159.147:/opt/soft/demo.tar /opt/soft/ 说明: 从10.6.159.147机器上的/opt/soft ...
- EncryptTransform
internal class EncryptTransform { //private const int c_MaxLengthOf_IV_DES = 4; //private const int ...
- (C#)WinForm窗体间传值
1.通过构造函数 特点:传值是单向的(不可以互相传值),实现简单 实现代码如下: 在窗体Form2中 int value1; string value2; public Form2 ( int v ...
- C#设计模式——职责链模式(Chain Of Responsibility Pattern)
一.概述 在软件开发中,某一个对象的请求可能会被多个对象处理,但每次最多只有一个对象处理该请求,对这类问题如果显示指定请求的处理对象,那么势必会造成请求与处理的紧耦合,为了将请求与处理解耦,我们可以使 ...
- 大话设计模式-->模板方法设计模式
在学习java的过程中,我们肯定听到过设计模式这名词,在行业中有这么一句话,若您能熟练的掌握23种设计模式,那么你便是大牛! 好了,废话不多说,今天我跟大家分享一下23种设计模式之一的 模板方法 设 ...
- 轻松解决MYSQL数据库连接过多的错误
1.数据库系统允许的最大可连接数max_connections.这个参数是可以设置的.如果不设置,默认是100.最大是16384. 2.数据库当前的连接线程数threads_connected.这是动 ...
- 【C#进阶系列】06 类型和成员基础
这些东西是基础中的基础,基本上是本书都会讲这个.但是很多东西到处都有,所以只捡了以下的这些写下来. 关于类型的可见性和可访问性 也就是public,internal这种东西,但是还是有个东西要提一下, ...
- 重新想象 Windows 8 Store Apps (36) - 通知: Tile 详解
[源码下载] 重新想象 Windows 8 Store Apps (36) - 通知: Tile 详解 作者:webabcd 介绍重新想象 Windows 8 Store Apps 之 通知 Tile ...
- 验证坐标在某片坐标区域内 php 代码
之前碰到的这样一个需求,要将公司的服务范围在地图中显示出来,并将用户每天的访问坐标进行统计看有多少用户是在所能达到的服务范围半径内. 以下是PHP代码的实现 (仅验证坐标在某片坐标区域内) <? ...
- .NET Core创建一个控制台(Console)程序
.NET Core版本:1.0.0-rc2 Visual Studio版本:Microsoft Visual Studio Community 2015 Update 2 开发及运行平台:Window ...