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 ...
随机推荐
- MySql (二)入门语句和基本操作
mysql的入门语句:查看服务器下的库 show databases; 创建库(数据库被创建后它的名字是不可以更改的) create database 数据库名; 2.1.插看当前所在的库 selec ...
- MFC_2.8 使用状态栏工具栏
使用状态栏工具栏 1.资源-添加-TOOLBAR 画图标.画了一个,第二个会出来. 2.头文件添加成员 CToolBar m_ToolBar; CStatusBar m_StatusBar; 3.初始 ...
- tee命令用法
用途说明 在执行Linux命令时,我们可以把输出重定向到文件中,比如 ls >a.txt,这时我们就不能看到输出了,如果我们既想把输出保存到文件中,又想在屏幕上看到输出内容,就可以使用tee命令 ...
- Moving Tables POJ - 1083 (思维)
题目大意 在一层楼上推桌子,每个空间一次只能推1种桌子,且消耗十分钟.可以同时推多个桌子,但是他们所占的空间不能是相交的如图 解法 真的很考验思维能力,首先考虑到这个走廊是有两排的,我瞬间想到了宿舍楼 ...
- uva 272 Tex中的引号(Tex Quotes)
TeX is a typesetting language developed by Donald Knuth. It takes source text together with a few ty ...
- Flask上下文流程图
如图:
- buf.readFloatBE()
buf.readFloatBE(offset[, noAssert]) buf.readFloatLE(offset[, noAssert]) offset {Number} 0 noAssert { ...
- Sigmoid Function
本系列文章由 @yhl_leo 出品,转载请注明出处. 文章链接: http://blog.csdn.net/yhl_leo/article/details/51734189 Sigmodi 函数是一 ...
- noip模拟赛 蒜头君的坐骑
分析:标准的棋盘dp问题. 如果没有技能,那么就很好做了,相当于传纸条的做法.有了技能的限制,我们就要加上一维表示用了多少次技能,这个时候转移就要用到dfs了,而且不能用填表法,要用刷表法,从当前位置 ...
- 测试出来了第一版代码--可以得到用户token啦
一版一版往前走啦... 先安装vs2010的学习版, 然后用codeblock来搞. 有一个msvcr100.dll这个文件需要和代码同级目录. 这样的好处是合规,然后,codeblock也可以用vs ...