What is this?

In JavaScript, the orientation of this is determined at call time, not creation time.

Global context

In the context of global execution this refers to the global object.

  • This is equivalent to the window object

  • var === this. === winodw.

    console.log(window === this); // true var a = 1; this.b = 2; window.c = 3; console.log(a + b + c); / / 6

In browsers this is equivalent to the window object, and if you declare some global variables, those variables will be the properties of this.

Function context

Inside a function, the value of this depends on how the function is called.

Direct call

thisPoint to a global variable.

function foo(){
  return this;
}
console.log(foo() === window); // true
Copy the code

Call (), the apply ()

thisPoint to the bound object.

var person = {
  name: "axuebin",
  age: 25
};
function say(job){
  console.log(this.name+":"+this.age+" "+job);
}
say.call(person,"FE"); // axuebin:25
say.apply(person,["FE"]); // axuebin:25
Copy the code

As you can see, we define a say function to output name, age, and job. There are no name and age attributes in the function. We bind this function to the object Person and output the attributes that belong to Person.

If you pass a raw value (String, Boolean, or number) as a binding object to this, the original value is converted to its object form (new String()), which is often referred to as “boxing.”

Call and apply are the same in terms of binding this, except for their second argument.

bind()

thisWill be permanently bound tobindThe first argument to.

Bind is similar to call and apply.

var person = {
  name: "axuebin",
  age: 25
};
function say(){
  console.log(this.name+":"+this.age);
}
var f = say.bind(person);
console.log(f());
Copy the code

Simulate the implementation of the Apply method

/ / Jane in the Function prototype. ApplyOne = Function (context) {/ / to get the first call to call the Function, with this you can get the context. Fn = this; context.fn(); delete context.fn; } var aaa = {name: "aaa", sayHello: function (age) {console.log(this.name); }}; var bbb = { name: "bbb", }; Sayhello. applyOne(BBB)//Copy the code

Arrow function

None of the arrow functions have their ownthisBoth point to the outer layer.

function Person(name){
  this.name = name;
  this.say = () => {
    var name = "xb";
    return this.name;
  }
}
var person = new Person("axuebin");
console.log(person.say()); // axuebin
Copy the code

In a callback function, as in a timer:

function foo() {  
  setTimeout(()=>{
    console.log(this.a);
  },100)
}
var obj = {
  a: 2
}
foo.call(obj);
Copy the code

As a method of an object

thisRefers to the object calling the function.

var person = {
  name: "axuebin",
  getName: function(){
    return this.name;
  }
}
console.log(person.getName()); // axuebin
Copy the code

Note:

var name = "xb";
var person = {
  name: "axuebin",
  getName: function(){
    return this.name;
  }
}
var getName = person.getName;
console.log(getName()); // xb
Copy the code

This refers to the global variable again.

Again, what this refers to depends on the function call.

As a constructor

thisIs bound to the new object being constructed.

Creating an object using a constructor actually performs several steps:

  1. Create a new object
  2. Point this to this object
  3. Assigning values to objects (properties, methods)
  4. Return this

So this is pointing to the object that we created.

function Person(name){
  this.name = name;
  this.age = 25;
  this.say = function(){
    console.log(this.name + ":" + this.age);
  }
}
var person = new Person("axuebin");
console.log(person.name); // axuebin
person.say(); // axuebin:25
Copy the code

As a DOM event handler

thisPoints to the element that triggered the event, which is the DOM node to which the initial event handler is bound.

var ele = document.getElementById("id");
ele.addEventListener("click",function(e){
  console.log(this);
  console.log(this === e.target); // true
})
Copy the code

HTML tags inline event handlers

thisPoints to the DOM element

<button onclick="console.log(this);" >Click Me</button>Copy the code

JQuery’s this

In many cases JQuerythisBoth point to DOM element nodes.

$(".btn").on("click",function(){
  console.log(this); 
});
Copy the code

conclusion

If you want to determine a function’s this binding, you need to find where the function is called directly. We can then determine the binding object of this by following four rules in order:

  1. bynewCall: Bind to the newly created object
  2. bycallorapply,bindCall: Binds to the specified object
  3. Called by context object: Binds to context object
  4. Default: global object

Note: The arrow function does not use the above binding rules and determines this based on the outer scope, inheriting the this binding of the outer function call.