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 ...
随机推荐
- Javascript起源...
Javascript的设计思路是这样的: (1)借鉴C语言的基本语法: (2)借鉴Java语言的数据类型和内存管理: (3)借鉴Scheme语言,将函数提升到"第一等公民"(fir ...
- 转载:第四弹!全球首个微信小程序(应用号)开发教程!通宵吐血赶稿,每日更新!
感谢大家支持!博卡君周末休息了两天,今天又回到战斗状态了.上周五晚上微信放出官方工具和教程了,推荐程序猿小伙伴们都去试一试,结合教程和代码,写写自己的 demo 也不错. 闲话不多说,开始更新! 第七 ...
- [ASP.NET] 使用 ASP.NET SignalR 添加实时 Web
ASP.NET SignalR 是为 ASP.NET 开发人员提供的一个库,可以简化开发人员将实时 Web 功能添加到应用程序的过程.实时 Web 功能是指这样一种功能:当所连接的客户端变得可用时服务 ...
- [Solution] 简单数字识别之Tesseract
图像识别涉及的理论:傅里叶变换,图形形态学,滤波,矩阵变换等等. Tesseract的出现为了解决在没有这些复杂的理论基础,快速识别图像的框架. 准备: 1.样本图像学习,预处理 (平均每1个元素出现 ...
- 常用vs快捷键
Ctrl+E,D ----格式化全部代码 Ctrl+A+K+FCtrl+E,F ----格式化选中的代码 Ctrl+K+FCTRL + SHIFT + B生成解决方案 Alt+B+B 或 F6 生成当 ...
- IDEA默认常用快捷键
作为Java的利器,IDEA属实是非常好用,参考网文总结其常用快捷键如下: Ctrl + /(Ctrl + Shift + /):注释或反注释指定的语句.这个是本人最喜欢的,所以排在第一位. Ctrl ...
- Mongoose 框架初学使用记录
嘛.... 最近由于需要使用HTTP服务端,原先是使用的Qt框架实现的HTTP服务端,然后发现有些缺陷导致我不得不放弃这个框架,也不是完全放弃,只是HTTP服务端这里不再使用Qt,用Qt做高并发真的有 ...
- css中important的用处
今天看代码时遇到一段不理解的地方. #note_content { line-height: 22px; border: #DEDEDE 1px solid; background: #FAFAFA; ...
- 优雅输出Javascript从Chrome浏览器
一般前端Web开发好的App中js脚本文件,为了节约流量,都会做最小化,甚至合并压缩处理.但在对于需要Debug已处理过Javascript文件就不太方便了,可读性太差了. 使用Goo ...
- Google OKR 目标管理体系学习
OKR 全称是「目标和关键成果」(Objectives and Key Results).它是Google在公司创立不足一年的时候,从Intel公司引入的目标管理系统,也常被认为是一套组织测评系统. ...