Effective JavaScript: Chapter II

Source: Internet
Author: User
Tags variable scope

1. Master Closures

Understand closures to learn three basic facts:

①javascript allows you to refer to variables defined outside of the current function;

For example:

function Makesandwich () {    var magicingredient = ' peanut butter ';     function Make (filling) {        return magicingredient + ' and ' + filling;    }     return Make (' Jelly ');} Makesandwich ();        // ' Peanut butter and jelly '

② even if an external function has been returned, the current function can still refer to the variable defined in the external function;

function Sandwichmaker () {    var magicingredient = ' peanut butter ';     function Make (filling) {        return magicingredient + ' and ' +filling;    }     return Make ;} var f = sandwichmaker (); F (' Jelly '); F (' bananas '); F (' marshmallows ') ;

The value of f is the internal make function, and the call to F is actually called the make function.

③ closures can update the values of external variables.

 function   box () { var  val = undefined;   return   {set:  function  (newval) {val = newval;}, get:  function  () {return   Val;}, type: function  () {typeof   Val;} };} Val b  = box (); B.type (); B.set ( 98.6

This example produces an object containing three closures, which are the set, get, and type properties of the three closures. They share access to the Val variable. The set closure updates the Val value, and then calls get and type to view the updated results.

3. workaround for JavaScript missing block-scoped scopes:

① creates a nested function and immediately calls it to force the creation of a local scope:

function Wrapelements (a) {    var result = [];      for (var i = 0, n = a.length; i < n; i + +) {        (function()            {var j = i;             function return a[j];};        }) ();    } result result;}    

② binds a local variable that is a formal parameter to Iife and passes its value as an argument.

Use Iife to create local scopes with caution, because wrapping blocks of code in a function can cause some subtle changes in the code block. First, the code block cannot contain any break statements and continue statements that jump out of a block. It is not legal to use break and continue outside of a function. Second, if the code block references this or the special arguments variable, Iife will change their meaning.

4. The official difference between an anonymous function and a named function expression is that the latter is bound to a variable with the same name as its function, and that variable will act as a local variable within that function. The real use of a named function expression is to debug.

5. in the system, the best way to avoid object contamination function expression scopes is to avoid adding properties to object.prototype at any time, and to avoid any use of local variables with the same name as the standard Object.prototype property.

6. naming function expressions can cause many problems and are not worth using.

7. the best way to write a portable function is to always avoid placing a function declaration in a local block or child statement. If you want to write a nested function declaration, you should place it at the outermost of its parent function, and if you need to conditionally select a function, the best way is to use Var declaration and function expression.

function return ' Global ';}     function Test (x) {        var g = f, result = [];         if (x) {            functionreturn' local ';}        Result.push (g ());        }    Result.push (g ());     return result;}

This eliminates the mystery of the inner variable scope. It is unconditionally bound as a local variable, and only the assignment statement is conditionally. The result is clear that the function is fully portable.

8. wrong way to use eval:

① allows it to interfere with scopes.

Calling the Eval function interprets the parameter as a JavaScript program. However, the program runs in the caller's local scope, and the global variables embedded in the program are created as local variables of the calling program.

function Test (x) {    eval ('var  y = x; ');     return y;    } Test (' hello ');   // ' Hello '

An easy way to ensure that the Eval function does not affect the outer scope is to run it in a definite nested scope.

var y =' global ';function  Test (SRC) {    (function  () {eval (src);}) ();     return y;} Test ("var y = ' local ';");   // ' Global 'test ("var z = ' local ';");   // ' Global '

9. Indirect call to eval function is better than direct call

The Eval function has the ability to access the entire scope of the call at that time.

Call Eval directly:

var x = ' global ';     function Test () {        var x = ' local ';         return eval (' x ');       } Test ();    // ' local ';

To invoke Eval indirectly:

var x = ' global ';     function Test () {        var x = ' local ';         var f = eval;         return f (' X ');    } Test ();

Binding the Eval function to another variable name, calling the function through the variable name causes the code to lose access to all local scopes.

A neat way to write an indirect call to the Eval function is to use the expression sequence operator (,) and a distinctly meaningless numeric literal.

(0, eval) (SRC)

Effective JavaScript: Chapter II

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.