This is a reference that is bound at run time and may be bound to different objects in different cases.

Default binding (for Windows) (function call pattern fn())

By default, this is bound to a global object, such as the Window object in the browser environment and the global object in node.js.

The following code shows this binding:

message = "Hello"; 

function test () { 
  console.log(this.message); 
}

test() // "Hello"
Copy the code

Implicit binding (who calls, to whom this points) (method call pattern obj.fn())

If a function is called from an object, this in the function is automatically implicitly bound as an object:

function test() {
	console.log(this.message); 
}

let obj = {
  message: "hello,world",
  test: test
}

obj.test() // "hello,world"
Copy the code

Explicit binding (also known as hard binding) (context-calling pattern, this points to whoever you want this to point to)

Hard binding => Call apply bind

You can explicitly bind:

function test() { console.log(this.message); } let obj1 = {message: "Hello world 123"} let obj2 = {message: Test.bind (obj2)() // "helloworld 456"} test.bind(obj2)() //" helloworld 456"Copy the code

New binding (constructor pattern)

In addition, this is bound when you create an object using new

When the constructor is called with new, a new object is created and bound to the constructor’s this:

function Greeting(message) {
	this.message = message;
}

var obj = new Greeting("hello,world")
obj.message // "hello,world"
Copy the code

Test:

let obj = { a: { fn: function () { console.log(this) }, b: 10 } } obj.a.fn() let temp = obj.a.fn; temp() // ------------------------------------------------------------- function Person(theName, TheAge) {enclosing name = theName enclosing the age = theAge} Person. The prototype. The sayHello = function () {/ / define functions the console. The log (this)} let Per = new Person("小黑", 18) per.sayhello ()Copy the code