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. js延时加载的方法

    js的延迟加载有助与提高页面的加载速度,以下是延迟加载的几种方法: 1.使用setTimeout延迟方法的加载时间 延迟加载js代码,给网页加载留出更多时间 <script type=" ...

  2. CAD在一个点构造选择集(网页版)

    主要用到函数说明: IMxDrawSelectionSet::SelectAtPoint 在一个点构造选择集.详细说明如下: 参数 说明 [in] IMxDrawPoint* point 点坐标 [i ...

  3. Java基础(八)--String(源码)、StringBuffer、StringBuilder

    String源码:基于jdk1.8 public final class String implements Serializable, Comparable<String>, CharS ...

  4. 解决header,footer等HTML5标签在IE(IE6/IE7/IE8)无效的方法

    HTML5的语义化标签以及属性,可以让开发者非常方便地实现清晰的web页面布局,加上CSS3的效果渲染,快速建立丰富灵活的web页面显得非常简单. HTML5的新标签元素有: <header&g ...

  5. 新安装数据库sqlserver2008r2,使用javaweb连接不上问题处理

    鼠标右键[计算机]-->[管理],打开界面如下: 选择自己数据库的实例名: 选择TCP/IP:右键[属性],将所有TCP动态端口的[0]删掉,TCP端口设为1433:重启服务,即可连接. PS: ...

  6. BigDecimal舍入规则

    1.ROUND_UP 舍入远离零的舍入模式. 在丢弃非零部分之前始终增加数字(始终对非零舍弃部分前面的数字加1). 注意,此舍入模式始终不会减少计算值的大小. 2.ROUND_DOWN 接近零的舍入模 ...

  7. 类模板成员函数默认值问题:an out-of-line definition of a member of a class template cannot have default arguments

    template <typename T> class A { ); }; template<typename T> ) { /* */ } 对于类似上文代码,VS编译器会报 ...

  8. WebStorm 格式化代码快捷键

    原文链接:https://kaifazhinan.com/webstorm-formatting-code-shortcuts/ 现在平时都是使用 VS Code 作为日常开发工具,偶尔会打开 Web ...

  9. Linux之iptables(六、rich规则)

    其它规则 当基本firewalld语法规则不能满足要求时,可以使用以下更复杂的规则 rich-rules 富规则,功能强,表达性语言 Direct configuration rules 直接规则,灵 ...

  10. Linux有几种安装软件的方式?????

    看了Windows后台软件安装的过程,想必Linux也是这样.拿RHEL7来打比方 最开始Linux上安装软件只提供源代码,需要自己去编译源代码,拷贝库文件等 RPM 红帽软件包管理器可以自动地执行上 ...