Let’s start with the normal this pointing problem

What is this: Automatically references the current method being called. The object before.

There are three cases that this refers to

  1. Obj.fun () this->obj in fun, automatically pointing to. In front of the object

  2. New Fun() This -> is the new object being created in Fun. New changes the this pointer inside the function, causing this to point to the object instantiating new

  3. Fun () and anonymous functions call this by default ->window. This inside the function refers to window by default

To return to the “this” problem in the callback function, let’s look at an example

Var Bob = {sname: "Bob," friends: [" Jack ", "Rose", "Tom", "Jerry"]. Intr (){this.friends.foreach (function(ele){console.log(this.sname+" 新 "+ele); }); } } Bob.intr(); </script>Copy the code

The results:

Knew Jack, knew Rose, knew Tom, knew Jerry

This in the callback function is referred to as the window by default, because it is essentially a callback inside the function, which does not. Object call before

How to solve:

Using the arrow function

Var Bob = {sname: "Bob," friends: [" Jack ", "Rose", "Tom", "Jerry"]. Intr (){this.friends.foreach (ele=>{console.log(this.sname+" 新 "+ele); }); } } Bob.intr(); </script>Copy the code

The result is:

Bob knows Jack, Bob knows Rose, Bob knows Tom, Bob knows Jerry

You can see that this inside the arrow function automatically points to this outside the callback function.

This in the arrow function:

The this object inside the function is the object at which it is defined, not used.

This is fixed, not because the arrow function has a mechanism to bind this, but because the arrow function does not have its own this, so the inner this is the outer code block’s this. Because it does not have this, it cannot be used as a constructor.

You can also permanently bind this using bind

Sname: "Bob," friends: [" Jack ", "Rose", "Tom", "Jerry"]. Intr (){this.friends.foreach (function(friend){console.log(this.sname+" friend "+friend); }.bind(this)); } } Bob.intr();Copy the code