This represents a reference to the current object, which is not fixed and will change as the execution context changes.

Remember the following summary of this, that’s the point!!

  1. In a method (which is not defined by the arrow function), this represents the object to which the method belongs;

  2. How to use this alone, this stands for global object;

  3. In functions, this represents the global object;

  4. In functions, in strict mode, this is undefined (undefined);

  5. In events, this represents the element that receives the event;

  6. Call () and apply() can refer to this to any object;


Sometimes it’s hard to tell a method from a function, so let’s write it down here

The difference between methods and functions:

First, let’s use examples to understand the difference between methods and functions:

Example 1:

// Example 1:
var person = {
  name:'leaf';
  age:26;
  getName:function(){
    console.log(this.name);
  }
}

person.getName();//leaf
Copy the code

The getName property is a method that belongs to a Person object. That is, the getName property belongs to the object method of Person. GetName cannot be referred to alone and can only be called by an object, such as Person.getName ().

Example 2:

// Example 2:
function demo(){
  console.log("I'm a function".this);
}

demo();
Copy the code

The demo above is a function that has its own functionality and can refer to demo() by itself.

In a method, this represents the object to which the method belongs; In functions, this represents the global object;

In Example 1 this represents the person object, and in Example 2 this represents the global object Window.

Here’s another example:

var name = "windowsName";
var person = {
  name: 'leaf'.getName: function () {
    console.log(this.name); }}var f = person.getName();
f();
//windowsName
Copy the code

Assign the person object method getName() to the variable f. The above code is equivalent to:

var name = "windowsName";
var person = {
  name: 'leaf'.getName: function () {
    console.log(this.name); }}var f = function getName(){
  console.log(this.name);
}
f();
//windowsName
Copy the code

All f is a function, in which this represents a global variable, so the output prints windowsName.

Summary of the difference between methods and functions:

  • Methods and objects bound together, cannot be referenced separately, can only be called through the object;

  • Functions have independent functions and can be referred to separately.

  • In a method, this represents the object to which the method belongs; In functions, this represents the global object;