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. share——Alpha版(内部测试版)发布

    我们产品的下载二维码: 使用说明: 后期会进行更新,文件下载位置

  2. iOS中NSAttributedString的使用--对关键字着色,以及处理html实例

    1,最近项目中用到了一个功能,一个很好的功能.就是用户在搜索的时候,搜索结果出来后对你输入的关键字进行红色标记.这样用户就很请楚的看到自己输入什么后会出现什么样子的结果.还有一个功能是,现在有一段文字 ...

  3. [Git]Please make sure you have the correct access rights and the repository exists

    这个问题是这样,需要在已有github账号的A机器上,再创建一个github账号,新账号创建完毕,将代码通过机器A push上之后,再另一台机器B,clone 这个项目时报出了如下错误: Permis ...

  4. poj2352 Stars【树状数组】

    Astronomers often examine star maps where stars are represented by points on a plane and each star h ...

  5. Flask保存或解压上传的文件

    import os import uuid import shutil import zipfile from flask import Flask, render_template, request ...

  6. Linux:使用root踢掉其他用户

     首先使用w命令查看所有在线用户:  执行命令: pkill -kill -t tty3 再用w命令查看是否已经强制踢掉: TTY 是终端的意思    TTY :0 表示root用户登陆图形化界面的终 ...

  7. gdb个人使用记录

    参考博客:https://blog.csdn.net/zdy0_2004/article/details/80102076 安装gdb,查看版本确认成功: sudo apt install gdb g ...

  8. 抽象类和接口有什么区别---https://blog.csdn.net/csdn_aiyang/article/details/71171886

    https://blog.csdn.net/csdn_aiyang/article/details/71171886 概念]   抽象类.具体类是相对的,并非绝对的.抽象是一种概念性名词,具体是一种可 ...

  9. JAVA学习课本内容总结

    二.基本类型 数组 枚举 1.基本类型 逻辑类型 boolean (true/false) 整数类型 byte(8位)  short(16)  int(32)  long(64) 浮点类型 float ...

  10. python中实现将普通字典dict转换为java中的treeMap

    上代码: from heapq import heappush,heappop from collections import OrderedDict def toTreeMap(paramMap): ...