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"  

  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,布布扣,bubuko.com

时间: 2024-11-02 12:03:58

JavaScript Patterns 2.2 - Minimizing Globals的相关文章

JavaScript Patterns 2.10 Naming Conventions

1. Capitalizing Constructors var adam = new Person(); 2. Separating Words camel case - type the words in lowercase, only capitalizing the first letter in each word. upper camel case, as in  MyConstructor(), lower  camel  case,  as  in  myFunction(),

JavaScript Patterns 5.4 Module Pattern

MYAPP.namespace('MYAPP.utilities.array'); MYAPP.utilities.array = (function () { // dependencies var uobj = MYAPP.utilities.object, ulang = MYAPP.utilities.lang, // private properties array_string = "[object Array]", ops = Object.prototype.toStr

JavaScript Patterns 7.1 Singleton

7.1 Singleton The idea of the singleton pattern is to have only one instance of a specific class. This means that the second time you use the same class to create a new object, you should get the same object that was created the first time. var obj =

JavaScript Patterns 2.7 Avoiding Implied Typecasting

Dealing with == and === false == 0 or "" == 0 return true. always use the === and !== operators that check both the values and the type of the expressions you compare: var zero = 0; if (zero === false) { // not executing because zero is 0, not f

JavaScript Patterns 3.7 Primitive Wrappers

Primitive value types: number, string, boolean, null, and undefined. // a primitive number var n = 100; console.log(typeof n); // "number" // a Number object var nobj = new Number(100); console.log(typeof nobj); // "object"  One reason

JavaScript Patterns 2 Essentials - Writing Maintainable Code

Revisiting the code after some time has passed requires: ? Time to relearn and understand the problem ? Time to understand the code that is supposed to solve the problem As the application matures, many other things happen that require your code to b

JavaScript Patterns 2.12 Writing API Docs

Free and open source tools for doc generation: the JSDoc Toolkit (http://code.google.com/p/jsdoc-toolkit/) and YUIDoc (http://yuilibrary.com/projects/yuidoc). Process of generating API documentation ? Writing specially formatted code blocks ? Running

JavaScript Patterns 2.11 Writing Comments

Document all functions, their arguments and return values, and also any interesting or unusual algorithm or technique. Think of the comments as hints to the future readers of the code; the readers need to understand what your code does without readin

JavaScript Patterns 4.7 Init-Time Branching

When you know that a certain condition will not change throughout the life of the program, it makes sense to test the condition only once. Browser sniffing (or feature detection) is a typical example. // BEFORE var utils = { addListener : function(el