This is my third article about getting started


Special application of the this binding rule

Ignoring to show bindings

If null or undefined is passed in an explicit binding, the explicit binding is ignored and the default rules are used.

function foo() {
  console.log(this);
}

var obj = {
  name: "zhangsan"}; foo.call(obj);// obj
foo.call(null); // window
foo.call(undefined); // window

var bar = foo.bind(null);
bar(); // window

var baz = foo.bind(undefined);
baz(); // window
Copy the code

Indirect function reference

Create an indirect reference to a function, using the default rules.

function foo() {
  console.log(this);
}

var obj1 = {
  name: "zhangsan".foo: foo,
};

var obj2 = {
  name: "lisi"}; obj1.foo();//obj
(obj2.foo = obj1.foo)();  // window
Copy the code

Arrow functions in ES6

Arrow functions in ES6 do not use the four binding rules for this, but are determined by this in the outer scope.

Simulate a network request
  • Using setTimeout to simulate network requests, how can data be stored in data after the request?

  • I need to get the OBJ object and set data

  • “This” is the window. We need to define var _this = this in the outer layer

  • Using _this in the setTimeout callback represents an obj object

    var obj = {
      data: [].getData: function() {
        var _this = this;
        setTimeout(function() {
          // Simulate the acquired data
          var res = ["abc"."cba"."nba"]; _this.data.push(... res); },1000);
      }
    }
    
    obj.getData();
    Copy the code

The above example was the most common approach before ES6. Starting with ES6, we would use the arrow function:

  • Why use this directly in the setTimeout callback?

  • Since the arrow function does not bind this, the this reference finds the corresponding this from the upper scope

    var obj = {
      data: [].getData: function() {
        setTimeout(() = > {
          // Simulate the acquired data
          var res = ["abc"."cba"."nba"];
          this.data.push(... res); },1000);
      }
    }
    
    obj.getData();
    Copy the code

In the example above, if getData is also an arrow function, who does this point to in the setTimeout callback?

  • The answer iswindow;
  • If you are still looking at the upper scope, you have found the global scope.
  • In the global scope,thisIt stands forwindow
var obj = {
  data: [].getData: () = > {
    setTimeout(() = > {
      console.log(this); // window
    }, 1000);
  }
}

obj.getData();
Copy the code