“This is the second day of my participation in the Gwen Challenge in November. See details: The Last Gwen Challenge in 2021”

In a word

Js this pointing problem is a pain point, but it is not difficult to understand the core idea: this pointing does not depend on the definition, but depends on the call

explain

Where this is defined, look up the scope to find the nearest function (arrow functions except, because es6 arrow functions do not have this) and see how the function is ultimately executed. The direction of this depends on how the function is called, not the definition.

Function calls generally fall into the following five situations

  1. As a function call, fun() this refers to a global Object. Note the strict mode problem (the strict mode global this refers to undefined). In browsers the global Object is window, and in Nodes the global Object is Object [global].

  2. As a method call, that is: obj.fun()/obj.bar.fun()/obj[‘fun’] this points to the object that eventually called the method

  3. Called as a constructor, i.e. : new Foo() This points to a new object Foo {}

    function foo(){
      console.log(this) // => foo {}
    }
    new foo()
    Copy the code
  4. Special calls, namely: fun.call()/fun.apply()/fun.bind() this, point to the first argument member of the binding or, if no argument is passed, to the global object

  5. Can't find function, global object

Master these 5 points to cover all the “this” questions. Can you answer the following tests correctly?

test

1.

var length = 10
function fn() {
  console.log(this.length)
}
const obj = {
  length: 5.method(fn) {
    fn()
    arguments[0]()
  }
}
obj.method(fn, 1.2)
Copy the code

This hit case 1: as a function call, this points to global, so access the length mounted to the window is 10. Second 3: As a method call, this points to arguments object {‘0’: [Function: fn], ‘1’: 1, ‘2’: 2}, so length prints 3

2,

const obj1 = {
  foo(){
    return () = > {
      console.log(this)
    }
  }
}
obj1.foo()()

const obj2 = {
  func : () = > {
    console.log(this)
  }
}
obj2.func()
Copy the code

First print obj1, this hit case 2: as a method call, look up this and skip the arrow function to find function foo, which is called by obj1 and points to obj1. Second browser print window, this hit case 5: If you can’t find function up, point to global

3,

class Person{
  say = () = > {
    console.log(this)}}const p = new Person()
p.say()
Copy the code

Print instance Person, this hit case 3: as a constructor call, class is the syntactic sugar for Function, essentially Function, and this points to instance P