Detailed explanation of this pointer in JavaScript

One: Introduction to this pointer

this is a keyword in the JavaScript language. It is an object automatically generated inside the function body when the function is running, and can only be used inside the function body. In short, this is the environment object where the function runs.

Two: the usage scenario of this

2.1. When executed as a general function, this refers to the global object

function test(){
    this.x = 1
    console.log(this.x)
}
test()//Expected output: 1

2.2. When executed as an object property, this refers to the superior object

function test(){
    console.log(this.x)
}
var obj = {}
obj.x = 1
obj.f = test
obj.f()//Expected output: 1

2.3. When called as a constructor, this refers to the new object

var x = 2
function test(){
    this.x = 1   
}
var obj = new test()
console.log(x)//Expected output: 2
console.log(obj.x)//Expected output: 1

2.4. When call, apply, and bind are invoked, this refers to the first parameter

let a = {}
let fn = function(){
    console.log(this)
}
fn.bind().bind(a)()//Expected output: windows

In the above code, no matter how many times we bind the function, this in fn is always determined by the first bind, so the result is always window

Three: Summary

Guess you like

Origin blog.csdn.net/qq_42691298/article/details/129516686