This is the 20th day of my participation in the August Wen Challenge.More challenges in August

priority

Having described the four rules for the this binding in function calls, all we need to do is find where the function is called and decide which rule to apply. What if there are multiple rules? This is where the priority of the rule comes into play. The default binding has the lowest priority of the four, so it can be ignored.

To determine this

We can determine which rule is applied to a function at a call location based on priority. It can be judged in the following order:

  1. Is the function called in new (new binding)? If so, this binds to the newly created object.
  2. Is the function called by call, apply (explicit binding), or hard binding? If so, this binds to the specified object.
  3. Is the function called in a context object (implicitly bound)? If so, this binds to that context object.
  4. If neither, use the default binding. (Binding undefined in strict mode, binding global object in non-strict mode)

Bind the exception

The behavior of the This binding can be unexpected in some scenarios. When you think you should use other binding rules, you actually use the default binding rules.

The ignored this

For example, use apply() to “expand” an array and pass in a function as an argument. Similarly, bind() can be a useful way of currizing functions:

    function (a,b){
        console.log('a:' + a + ',b:' + b);
    }
    foo.apply(null[2.3]);    //a:2,b:3
    var bar = foo.bind(null.2);
    bar(3); //a:2,b:3
Copy the code

Both methods require passing in an argument as the binding object for this. If the function doesn’t care about this, it still needs to pass in a placeholder value, in which case null looks fine. However, always using NULL to ignore this bindings can have side effects. If a function does use this, the default binding rule binds this to the global object. PS: The above example can be used with the expansion operator after ES6… To replace apply)

So we can pass in a special object to which we can bind this without causing any side effects.

    function foo(a,b){
        console.log('a:' + a + ',b:' + b);
    }
    var Ø = Object.create(null); Foo. Apply (Ø, [2.3]);    //a:2,b:3
    varThe bar = foo. Bind (Ø,2);
    bar(3); //a:2,b:3
Copy the code