[JS Grammar scope and binding icon

Cause: Scope climbing

  • JavaScript allowed inside the body of the function, refer to the current environment of other variables.
  • The current environment variable is not found, then climb onto the tile floor looking until you climb to the global (window) so far.
  • this refers to is the current environment, so its value is decided according to the environment when the function is called, it is not the same.

A way to bind: bind

  • bind can specify any context function.
  • bind handler will not be executed immediately, only to return a new function.

Binding Second way: call / apply

  • In the binding terms of scope, the same functions both call / apply, can be replaced. Except that parameters passed way.
  • call / apply handler is called immediate, it does not return a new function. So the difference between the way that bind usage scenario, rather than function.
  • This mode is mainly used
    • When the class definition, the current lending environment, to achieve the effects of a succession:
    function Product(name, price) {
      this.name = name;
      this.price = price;
    }
    function Food(name, price) {
      Product.call(this, name, price); 
      // <==> Product.apply(this, [name, price]);
      // <==> Product.bind(this, name, price)();
      this.category = 'food';
    }
    console.log(new Food('cheese', 5));
    • When the function calls to other environments as this:
    function greet() {
      var reply = [ this.animal, 'typically sleep between', this.sleepDuration ].join(' ');
      console.log(reply);
    }
    var obj = {
      animal: 'cats', sleepDuration: '12 and 16 hours'
    };
    greet.call(obj);  // cats typically sleep between 12 and 16 hours

Reference material

Guess you like

Origin www.cnblogs.com/mazhaokeng/p/11518825.html