preface

This article was first published on the author’s personal blog.

If there is any improper expression in the reading process, I hope to give you advice.

This chapter uses code examples to simplify the use of this. Read the passage and understand the directions of this in different situations.

The illustration

The next part will focus on this picture.

Common function

Whoever called the function is this.

Eg:

function foo() {
  console.log(this.a)
}
var a = 1
foo()

const obj = {
  a: 2,
  foo
}
obj.foo()

const c = new foo()
Copy the code
  • Direct callfoo, no matterfooWhere to put it,thisIt must bewindow.
  • obj.foo().objI called the function, sothisisobjObject.
  • fornewSpeaking,thisBound forever tocAbove, it will not be changed in any waythis.

This in the arrow function

The arrow function’s this does not apply to other rules, but depends on the outer (functional or global) context.

Eg:

const foo = {
	fn: function() {
    setTimeout(() = > {
      console.log(this)}}}console.log(foo.fn())
// {fn: f}
Copy the code

Arrow functions do not have this. This in arrow functions depends only on the this of the first normal function that wraps the arrow function. In addition, arrow functions using functions such as bind are invalid.

bind/call/apply

Apply, call, and bind can modify this.

Eg:

    var a = {
        name : "Cherry".func1: function () {
            console.log(this.name)
        },

        func2: function () {
            setTimeout(  function () {
                this.func1()
            }.bind(a)(),100); }}; a.func2()// Cherry
Copy the code