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 ...
随机推荐
- Spring框架系列(三)--Bean的作用域和生命周期
Bean的作用域 Spring应用中,对象实例都是在Container中,负责创建.装配.配置和管理生命周期(new到finalize()) Spring Container分为两种: 1.BeanF ...
- Python爬虫:抓取手机APP的数据
摘要 大多数APP里面返回的是json格式数据,或者一堆加密过的数据 .这里以超级课程表APP为例,抓取超级课程表里用户发的话题. 1.抓取APP数据包 表单: 表单中包括了用户名和密码,当然都是加密 ...
- Linux kernel-汇编基础
mov ASSEMABLE C LANGUAGE movl %eax,%edx edx = eax; --->register mode movl $0x123,%edx edx = 0x123 ...
- extjs动态插入一列
StdDayWordQuery:function(btn,event){ var form=Ext.getCmp('queryFormSDW'); var userNameORuserCode = f ...
- 每日命令:(11)nl
nl命令在linux系统中用来计算文件中行号.nl 可以将输出的文件内容自动的加上行号!其默认的结果与 cat -n 有点不太一样, nl 可以将行号做比较多的显示设计,包括位数与是否自动补齐 0 等 ...
- 部署live555到云
1.下载live555源码: wget http://www.live555.com/liveMedia/public/live.2017.10.28.tar.gz 2.解压源码包: ...
- idea 获取当前git最新分支
菜单栏VCS->选中Git 选择Fetch 获取最新分支
- CentOS服务器上部署 oracle10gr2
1.下载Centos系统 Linux 镜像文件. 推荐使用 CentOS5.4,下载地址:http://isoredirect.centos.org/centos/5/isos/i38 ...
- RxJava如何结合观察者与链式处理
RxJava如何结合观察者与链式处理 Author: Dorae Date: 2018年12月3日17:10:31 转载请注明出处 一.概述 首先问自己几个问题,如果非常清楚这几个问题的目的与答案,那 ...
- [kuangbin带你飞]专题六 最小生成树 N - 畅通工程再续
相信大家都听说一个“百岛湖”的地方吧,百岛湖的居民生活在不同的小岛中,当他们想去其他的小岛时都要通过划小船来实现.现在政府决定大力发展百岛湖,发展首先要解决的问题当然是交通问题,政府决定实现百岛湖的全 ...