The direction of this can be confusing in many cases, but I am sure that you will be able to understand the direction of this after reading this article.

Who does this point to in different scenarios:

One: pure function calls

var x = 1;
function test() {
	console.log(this.x)		// Point to window and print 1
}
test()		// This is a shorthand for window.test()
Copy the code

This is the test method called by the window, so this in the function body refers to the window. Two: method calls as objects

function test () {
	console.log(this.x)		// Point to obj, output 2
}
var obj = {};
obj.x = 2;
obj.m = test;
obj.m();
Copy the code

The test function is called as a method on obj, so this in test refers to obj. Three: called as a constructor

var x = 4;		// Define global variables for testing purposes
function Test () {
	this.x = 11;	/ / this point newObj
}
var newObj = new Test();
console.log(newObj.x)	/ / output 11
console.log(x)		// The output is 4, indicating that the global variable is not affected by this.x
Copy the code

Four: after apply is invoked

var x = 0;
function test() {
	console.log(this.x);
}
var obj = {};
obj.x = 1;
obj.m = test;
obj.m.apply();	/ / 0
test.apply(obj);	/ / 1
new test();
test.apply();	/ / 0
Copy the code

Apply () is a method of a function that changes the object on which the function is called. Its first argument represents the changed object on which the function was called. So, in this case this refers to the first parameter. For details on how other methods that change this, such as bind(),call() and apply, can be found here: Changing the method to which this points

Conclusion:

  1. Usually in a function this refers to the object on which the function is called.
  2. The this in the event function usually refers to the event source element to which the event is bound
  3. The constructor’s this, which calls the constructor to create an object using new, usually refers to the object created by new
  4. Global-scoped this usually refers to a global object (window in browsers)

In a word:

We can use a simple and easy to remember to describe the problem of this pointing to: who calls who!