JavaScript Common Pattern
来源:互联网 发布:js useragent 编辑:程序博客网 时间:2024/06/03 20:18
Anonymous Closures
This is the fundamental construct that makes it all possible, and really is the single best feature of JavaScript. We’ll simply create an anonymous function, and execute it immediately. All of the code that runs inside the function lives in a closure, which provides privacy and state throughout the lifetime of our application.
(function () {// ... all vars and functions are in this scope only// still maintains access to all globals}());
Global Import
JavaScript has a feature known as implied globals. Whenever a name is used, the interpreter walks the scope chain backwards looking for a var
statement for that name. If none is found, that variable is assumed to be global. If it’s used in an assignment, the global is created if it doesn’t already exist. This means that using or creating global variables in an anonymous closure is easy. Unfortunately, this leads to hard-to-manage code, as it’s not obvious (to humans) which variables are global in a given file.
Luckily, our anonymous function provides an easy alternative. By passing globals as parameters to our anonymous function, we import them into our code, which is both clearer and faster than implied globals. Here’s an example:
(function ($, YAHOO) {// now have access to globals jQuery (as $) and YAHOO in this code}(jQuery, YAHOO));
Module Export
Sometimes you don’t just want to use globals, but you want to declare them. We can easily do this by exporting them, using the anonymous function’s return value. Doing so will complete the basic module pattern, so here’s a complete example:
var MODULE = (function () {var my = {},privateVariable = 1;function privateMethod() {// ...}my.moduleProperty = 1;my.moduleMethod = function () {// ...};return my;}());Notice that we’ve declared a global module named
MODULE
, with two public properties: a method namedMODULE.moduleMethod
and a variable named MODULE.moduleProperty
. In addition, it maintainsprivate internal state using the closure of the anonymous function.- JavaScript Common Pattern
- Javascript Pattern Module pattern
- Common Javascript
- Common JavaScript Functions
- Observer pattern in Javascript
- JavaScript Observer Pattern 接口
- Observer pattern in JavaScript
- 《javascript pattern》要点概括
- javascript Prototype Pattern
- 40款 Javascript common plugins
- JavaScript Module Pattern: In-Depth
- CSharp mimicking JavaScript design pattern
- JavaScript 模块化编程 - Module Pattern
- JavaScript 模块化编程 - Module Pattern
- JavaScript 模块化编程 - Module Pattern
- Filter Bank Common Spatial Pattern (FBCSP) in Brain-Computer Interface
- 《javascript pattern》— javascript的继承
- 【common】JavaScript ----- 对象转化为json字符串
- Java 环境变量配置方法详解
- 完美契合,实现最大团队工作效率
- js数组的操作 【转】
- 面试 1
- 不按回车就接受一个字符输入
- JavaScript Common Pattern
- 动态连接库之基础篇
- 面试 2
- 关于Js调试
- Intel HD Graphics
- 面试 3
- Shark Machine Learning Library --之运行篇
- 怎样提高游戏的文件读写效率
- 组合框里添加复选框的方法