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"  
  1. The problem with Globals
    • Naming collisions
      1. 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

      2. 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.

  2. 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"  
  3. 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;
    
    }());    
  4. 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...
    }   
  5. 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的更多相关文章

  1. 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 ...

  2. JavaScript Patterns 5.4 Module Pattern

    MYAPP.namespace('MYAPP.utilities.array'); MYAPP.utilities.array = (function () { // dependencies var ...

  3. JavaScript Patterns 6.7 Borrowing Methods

    Scenario You want to use just the methods you like, without inheriting all the other methods that yo ...

  4. JavaScript Patterns 6.6 Mix-ins

    Loop through arguments and copy every property of every object passed to the function. And the resul ...

  5. JavaScript Patterns 6.5 Inheritance by Copying Properties

    Shallow copy pattern function extend(parent, child) { var i; child = child || {}; for (i in parent) ...

  6. JavaScript Patterns 6.4 Prototypal Inheritance

    No classes involved; Objects inherit from other objects. Use an empty temporary constructor function ...

  7. JavaScript Patterns 6.3 Klass

    Commonalities • There’s a convention on how to name a method, which is to be considered the construc ...

  8. JavaScript Patterns 6.2 Expected Outcome When Using Classical Inheritance

    // the parent constructor function Parent(name) { this.name = name || 'Adam'; } // adding functional ...

  9. 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 ...

随机推荐

  1. php获取文件扩展名

    <?php $path = 'http://www.wstmart.net/doc.html'; $ext = getExt($path); echo $ext; // 方法1 function ...

  2. 模板—AC自动机

    #include<iostream> #include<cstdio> #include<cstring> using namespace std; struct ...

  3. Linux kernel-汇编基础

    mov ASSEMABLE C LANGUAGE movl %eax,%edx edx = eax; --->register mode movl $0x123,%edx edx = 0x123 ...

  4. 散列(hash)

    散列(hash)是常用的算法思想之一,在很多程序中都会有意无意地使用到. 先来看一个简单的问题:给出N个正整数,再给出M个正整数,问这M个数中每个数分别是否在N个数中出现过. 例如N=5,M=3,N个 ...

  5. enote笔记语言(5)——其他(ver0.2)

    章节:其他   ((主:单词))                               用来醒目地强调这个句子中哪个词语作主语 sentence:                         ...

  6. python 爬取微信好友列表和个性签名,绘制个性签名云图

    python爬取微信好友列表和个性签名,绘制个性签名云图 1. 简要介绍 本次实验主要用到下面几个库 : 1)itchat---用于微信接口,实现生成QR码,用于微信扫描登陆 2)re(正则化)--- ...

  7. ACM-ICPC 2018 徐州赛区网络预赛 J. Maze Designer

    传送门:https://nanti.jisuanke.com/t/31462 本题是一个树上的问题:结点间路径问题. 给定一个有N×M个结点的网格,并给出结点间建立墙(即拆除边)的代价.花费最小的代价 ...

  8. POJ2528 Uva10587 Mayor's posters

    The citizens of Bytetown, AB, could not stand that the candidates in the mayoral election campaign h ...

  9. hdu 3062 2-sat

    #include<stdio.h> #include<string.h> #define N 2100 struct node { int u,v,next; }bian[N* ...

  10. 推销员(codevs 5126)

    题目描述 Description 阿明是一名推销员,他奉命到螺丝街推销他们公司的产品.螺丝街是一条死胡同,出口与入口是同一个,街道的一侧是围墙,另一侧是住户.螺丝街一共有N家住户,第i家住户到入口的距 ...