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. MySQL学习笔记(十二)__连接查询(一)

    连接查询含义:又称多表查询,当查询的字段来自多个表时,就会用到连接查询 笛卡尔乘积现象:表1 有 m 行,表2 有 n 行,结果 = m*n 行发生原因:没有有效的连接条件如何避免:添加有效的连接条件 ...

  2. vue启动

    首先在终端terminal连上npm 镜像库 npm config set registry https://registry.npm.taobao.orgnpm installnpm run loc ...

  3. python的webservice请求

    1.pip install client 2.pip install suds-jurko #coding=utf-8from suds.client import Clientimport time ...

  4. A useful logger function in C project.

    #cat log.c #include <stdio.h> #include <stdlib.h> #include <string.h> #include < ...

  5. 3D NAND闪存是个啥?让国内如此疯狂

    Repost: https://news.mydrivers.com/1/477/477251.htm 上个月底武汉新芯科技主导的国家级存储器产业基地正式动工,在大基金的支持下该项目将投资240亿美元 ...

  6. 个人总结的常用java,anroid网站

    http://blog.csdn.net/wanghao200906/article/details/49334987

  7. 洛谷——P1549 棋盘问题(2)

    P1549 棋盘问题(2) 搜索||打表 #include<cstdio> #include<cstring> #include<iostream> #includ ...

  8. Oracle创建用户、角色、授权、建表空间

    oracle数据库的权限系统分为系统权限与对象权限.系统权限( database system privilege )可以让用户执行特定的命令集.例如,create table权限允许用户创建表,gr ...

  9. linux初步学习有感

    经过了一段时间对linux的接触,从最开始接触到的deepin到后来我最喜欢的KaliLinux,感受到了这个我曾经并不了解的操作系统的独特魅力. 我是到了大学才知道linux这个系统的,但是在小时候 ...

  10. UVALive 6510 Stickers

    Stickers Time Limit: 3000ms Memory Limit: 131072KB This problem will be judged on UVALive. Original ...