JavaScript elevation Third Edition Notes - function expression

1⃣️ recursive

Factorial function:

function factorial(num){
        if (num <= 1){
  return 1;
} else { 6
         return num * factorial(num-1);
    }
}

A modification: (arguments.callee pointer to the function being performed, decoupling)

function factorial(num){
    if (num <= 1){
        return 1;
    } else {
        return num * arguments.callee(num-1);
} }

:( solve converted two strict mode can not be used arguments.callee)

var factorial = (function f(num){
        if (num <= 1){
            return 1;
        } else {
            return num * f(num-1);
} });

Closure scope chain 2⃣️

function createComparisonFunction(propertyName) {
        return function(object1, object2){
            var value1 = object1[propertyName];
            var value2 = object2[propertyName];
            if (value1 < value2){
                return -1;
            } else if (value1 > value2){
                return 1;
            } else {
                return 0;
            } 
}; }
var compare = createComparisonFunction("name");
var result = compare({ name: "Nicholas" }, { name: "Greg" });

After the anonymous function is returned from the createComparisonFunction (), which is initialized to the scope chain active objects and global variables to the target function comprises createComparisonFunction ().

so, the scope chain contains the active object createComparisonFunction compare functions (local function and local attributes, the above code is not reflected) and the global variable objects See the examples below:

    var count = 100;
    var a = 2;
    function create(){
      var count = 10;
      return function(){
        console.log(count + a);
      }
    };
    var b = create();
    b();

This is typical of a closure, as mentioned above, b is initialized to the scope chain active object create function (count = 10) and the global variable (a = 2, count = 100); therefore perform B () time, count + a = 10 + 2 = 12;

Why is 10 + 2, instead of 100 + 2 Look at this blog:? JS scope chain.

 

Guess you like

Origin www.cnblogs.com/eco-just/p/11327892.html