Summarize
- Global environment ➡️ window
- Normal function ➡️ window or undefined
- Constructor ➡️ Constructed Example
- Arrow function ➡️ This in outer scope when defining
- Object method ➡️ This object
- call(), apply(), bind() ➡️First parameter
Global environment
This points to a window object whether in strict mode or not.
(this === window) // true
// Strict mode'use strict' (this === window) // true
Normal functions
- Normal mode
- This points to the window object
function test() { return this === window } (test()) // true
- This points to the window object
- Strict mode
- This value is undefined
// Strict mode'use strict' function test() { return this === undefined } (test()) // true
- This value is undefined
Constructor
When a function is used as a constructor, this points to the constructed instance.
function Test() { = 1 } let test1 = new Test() () // 1
Arrow function
When a function is an arrow function, this points to this value in the previous scope when the function is defined.
let test = () => { return this === window } (test()) // true
let obj = { number: 1 } function foo() { return () => { return } } let test = (obj) (test()) // 1
Object method
When a function is used as a method of an object, this points to the object.
let obj = { number: 1, getNumber() { return } } (()) // 1
call()、apply()、bind()
- When calling the call() and apply() methods of the function, this function points to the first parameter passed in.
- When calling the function's bind() method, the returned new function's this point to the first parameter passed in.
let obj = { number: 1 } function test(num) { return + num } ((obj, 1)) // 2 ((obj, [2])) // 3 let foo = (obj, 3) (foo()) // 4
This is the article about this detailed explanation of this problem-oriented case in JavaScript. For more related content in this problem-oriented content in JavaScript, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!