JavaScript Patterns 2.2 Minimizing Globals
Access a global variable in a browser environment:
myglobal = "hello"; // antipattern console.log(myglobal); // "hello" console.log(window.myglobal); // "hello" console.log(window["myglobal"]); // "hello" console.log(this.myglobal); // "hello"
- The problem with Globals
- Naming collisions
- Code not written by developers
• A third-party JavaScript library
• Scripts from an advertising partner
• Code from a third-party user tracking and analytics script
• Different kinds of widgets, badges, and buttons
- Implied globals
meaning that any variable you don't declare becomes a property of the global object.
Solution - Use var to declare variable inside the function.
function sum(x, y) { var result = x + y; return result; } // antipattern, do not use function foo() { var a = b = 0; // a is local but b becomes global // ... } // The right way function foo() { var a, b; // ... a = b = 0; // both local }
- portability
Code to run in different environments (hosts), it's dangerous to use globals because you can accidentally overwrite a host object that doesn't exist in your original environment (so you thought the name was safe to use) but which does in some of the others.
- Side Effects when Forgetting var
Difference between implied globals and explicitly defined ones—the difference is in the ability to undefine these variables using the delete operator
• Globals created with var(those created in the program outside of any function) cannot be deleted.
• Implied globals created without var(regardless if created inside functions) can be deleted.
// define three globals var global_var = 1; global_novar = 2; // antipattern (function () { global_fromfunc = 3; // antipattern }()); // attempt to delete delete global_var; // false delete global_novar; // true delete global_fromfunc; // true // test the deletion typeof global_var; // "number" typeof global_novar; // "undefined" typeof global_fromfunc; // "undefined"
- Access to the Global Object
Access the global object without hard-coding the identifier window, you can do the following from any level of nested function scope:
var global = (function () { return this; }());
- Single var Pattern
• Provides a single place to look for all the local variables needed by the function
• Prevents logical errors when a variable is used before it's defined (see "Hoisting: A Problem with Scattered vars" )
• Helps you remember to declare variables and therefore minimize globals
• Is less code (to type and to transfer over the wire)
function func() {
var a = 1,
b = 2,
sum = a + b,
myobject = {},
i,
j;
// function body...
}Note: all uninitialized and declared variables are initialized with the value undefined
function updateElement() {
var el = document.getElementById("result"), style = el.style; // do something with el and style...
} - Hoisting: A problem with Scattered vars
JavaScript enables you to have multiple var statements anywhere in a function, and they all act as if the variables were declared at the top of the function.
// antipattern myname = "global"; // global variable function func() { // same as -> var myname = undefined; alert(myname); // "undefined" var myname = "local"; alert(myname); // "local" } func();
JavaScript Patterns 2.2 Minimizing Globals的更多相关文章
- 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 5.4 Module Pattern
MYAPP.namespace('MYAPP.utilities.array'); MYAPP.utilities.array = (function () { // dependencies var ...
- 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 Patterns 6.6 Mix-ins
Loop through arguments and copy every property of every object passed to the function. And the resul ...
- 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 6.4 Prototypal Inheritance
No classes involved; Objects inherit from other objects. Use an empty temporary constructor function ...
- JavaScript Patterns 6.3 Klass
Commonalities • There’s a convention on how to name a method, which is to be considered the construc ...
- JavaScript Patterns 6.2 Expected Outcome When Using Classical Inheritance
// the parent constructor function Parent(name) { this.name = name || 'Adam'; } // adding functional ...
- JavaScript Patterns 6.1 Classical Versus Modern Inheritance Patterns
In Java you could do something like: Person adam = new Person(); In JavaScript you would do: var ada ...
随机推荐
- MFC_2.10选项卡控件的封装
选项卡控件的封装 1.新建默认MFC项目 2.添加资源Dialog,属性style改child,边框改none,添加类取名CMyDialog1: 同理,CMyDialog2: 3.类向导,添加MFC类 ...
- 梦想CAD控件安卓控件事件
MxDrawActivity.commandEvent 命令调用事件. 参数 说明 int iCommand 命令ID,这个ID用户自已来取的,只要多个命令ID不重复就可以 代码实现如下: publi ...
- PHP 加密:Password Hashing API
PHP 5.5 之后引入 Password hashing API 用于创建和校验哈希密码,它属于内核自带,无需进行任何扩展安装和配置.它主要提供了四个函数以供使用: password_hash(): ...
- 【转载】dubbo约束的引入(解决eclipse中报错问题)
在采用分布式系统架构时,我们会经常使用到阿里巴巴的dubbo的分布式框架. 在相关xml配置了dubbo的约束依赖后,即使能上网eclipse.myeclipse等IDE也是无法识别dubbo的相关约 ...
- JAVA基础——异常--解析
简介 异常处理是java语言的重要特性之一,<Three Rules for effective Exception Handling>一文中是这么解释的:它主要帮助我们在debug的 ...
- php第二十六节课
会话购物车 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w ...
- ie7下设置z-index无效如何解决?
ie7下z-index无效的问题之前做练习的时候遇到过,百度解决掉之后就丢脑后了.今天项目中又发现这个bug,无奈又去百度,这次还是记下来,节省了百度的时间还能小装一把... 需求是这样的: 页面中的 ...
- 04StringBuffer相关知识、Arrays类、类型互换、正则、Date相关
04StringBuffer相关知识.Arrays类.类型互换.正则.Date相关-2018.7.12 1.StringBuffer A:StringBuffer的构造方法: public Strin ...
- Go:值类型、引用类型
值类型,变量存的就是值本身: in系列t.float系列.bool.string.数组和struct 引用类型,变量存的是一个地址,这是地址存的才是值本身: 指针.slice.map.chan.int ...
- 长久不用的mysql报错ERROR 2002 (HY000): Can't connect to local MySQL server through socket '/tmp/mysql.sock' (2)
mac上安装过mysql: 然而,尝试连接时报错: $ mysql -u root -p Enter password: ERROR 2002 (HY000): Can't connect to lo ...