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 ...
随机推荐
- Android 常见工具类封装
1,MD5工具类: public class MD5Util { public final static String MD5(String s) { char hexDigits[] = { '0' ...
- Mysql学习笔记(十)存储过程与函数 + 知识点补充(having与where的区别)
学习内容:存储程序与函数...这一章学的我是云里雾里的... 1.存储过程... Mysql存储过程是从mysql 5.0开始增加的一个新功能.存储过程的优点其实有很多,不过我觉得存储过程最重要的 ...
- shell join 参数详细说明
join类似db里面的join方法,同样有left join right join inner join等 指定参数-a 可以指定join的方式. -a1表示显示第一个文件中不匹配的行,即为left ...
- css中position与z-index
position属性 在css中,position属性用来控制元素的位置信息,其取值共有4种,即static.relative.absolute.fixed. 静态定位(static) 若没有指定po ...
- document.documentElement.clientWidth
document.documentElement.clientWidth 摘自:http://blog.sina.com.cn/s/blog_6f1f9ead0100n1f6.html 关于获取各种浏 ...
- php实现的IMEI限制的短信验证码发送类
php实现的IMEI限制的短信验证码发送类 <?php class Api_Sms{ const EXPIRE_SEC = 1800; // 过期时间间隔 const RESEND_SEC = ...
- 【C#进阶系列】03 配置文件管理与程序集的引用版本重定向
先来点与标题不相关的: CLR支持两种程序集:弱命名程序集和强命名程序集. 两者的区别在于强命名程序集使用发布者的公钥和私钥进行签名.由于程序集被唯一性地标识,所以当应用程序绑定到强命名程序集时,CL ...
- 自己动手搞定支付宝手机网站支付接口 FOR ECShop
支付宝WAP网站版本的支付接口网上整合的比较少,看到很多网站在卖,顿觉无语. 主要是得自己查看支付宝官方提供的SDK中的开发文档. 支付宝sdk下载地址:https://doc.open.alipay ...
- LGLAlertView 提示框
使用与iOS8 以后,只是把系统的UIAlertController进行了封装,省的每次用的时候要写很多的代码.封装后只需要一句代码即可 , deome 地址:https://github.com/l ...
- mongodb学习3---mongo的MapReduce
1,概述MapReduce是个非常灵活和强大的数据聚合工具.它的好处是可以把一个聚合任务分解为多个小的任务,分配到多服务器上并行处理.MongoDB也提供了MapReduce,当然查询语肯定是Java ...