One article to understand this point

Insert image description here



I. Introduction

This pointing problem in JS - Nuggets

In JavaScript, the this keyword represents the context object of the currently executing code. Its value depends on how the function is called. this can refer to the global object (the window object in browsers ), to the current object (for example, within an object method), or to a newly created instance when the object is created using a constructor.

2. Arrow function

const obj = {
    
    
    fun1: function () {
    
    
        console.log(this);
    },
    fun2: () => {
    
    
        console.log(this);
    }
}

obj.fun1(); // obj
obj.fun2(); // window
  • The this pointer of an arrow function is determined when the function is defined, not at runtime.
  • This inside the arrow function points to this in the outer layer
  • The this pointer of the arrow function cannot be changed, even if the call, apply or bind methods are used. Therefore, you need to pay attention to its this pointer when using arrow functions.

3. new points to

// class Person {} 和 function Person(name, age) 都可以用来定义一个对象的构造函数,但它们有一些区别。

// 语法:class 是 ES6 中新增的语法,用于定义类和构造函数,而 function 是 JavaScript 中早期就存在的语法,用于定义函数和构造函数。

// 继承:class 支持更加简洁和灵活的继承方式,可以使用 extends 关键字来继承其他类,而 function 只能使用原型链来实现继承。

// 方法定义:在 class 中,方法可以直接定义在类的内部,而在 function 中,方法需要定义在构造函数的原型对象上。

class Person {
    
    
    constructor(name, age) {
    
    
        this.name = name;
        this.age = age;
    }

    print() {
    
    
        console.log(this);
    }
}

const p1 = new Person('张三', 18);
p1.print()

  • When you use the new keyword to call a function, the this point in the function must be an instance object.

4. bind

const person = {
    
    
    name: 'Alice',
    age: 20
};

function sayHello() {
    
    
    console.log(`Hello, my name is ${
      
      this.name}, I'm ${
      
      this.age} years old.`);
}

const sayHello2 = sayHello.bind(person);
sayHello2(); // 输出 "Hello, my name is Alice, I'm 20 years old."
  • Usage : bind(thisArg, arg1, arg2, /* …, */ argN)
  • The bind method is a method in JavaScript used to change the this keyword pointed to when a function is executed. It returns a new function that has the same function body as the original function, but the this keyword is bound to the specified object.
  • It should be noted that the bind method will not modify the this keyword of the original function, but will return a new function, but it will not be called immediately. At the same time, the new function created using the bind method can be called multiple times. The same binding object will be used each time it is called, and this will not be modified.

In addition, the bind method can also be used to implement function currying, which is the process of converting a multi-parameter function into a single-parameter function sequence. For example:

function add(x, y) {
    
    
    return x + y;
  }
  
  const add5 = add.bind(null, 5);
  console.log(add5(3)); // 输出 8
  console.log(add5(7)); // 输出 12

5. call and apply

const person = {
    
    
  name: 'Alice',
  age: 20
};

function sayHello() {
    
    
  console.log(`Hello, my name is ${
      
      this.name}, I'm ${
      
      this.age} years old.`);
}

sayHello.apply(person);
sayHello.call(person);
  • Both call and apply can call the original function immediately, and can specify the this keyword and parameter list when the function is executed.

6. The difference between bind call apply

const name = '小王', age = 17

const obj = {
    
    
    name: '小张',
    objAge: this.age,
    myFun: function (fm, t) {
    
    
        console.log(this.name + '年龄' + this.age)
        console.log(fm + t)
    }
}

const db = {
    
    
    name: '小李',
    age: 18
}

obj.myFun.bind(db, '北京', '上海')()
obj.myFun.call(db, '北京', '上海')
obj.myFun.apply(db, ['北京', '上海'])
  • The same point: both will change the this point of the function.
  • Binding is different:
    • bind will not change the this keyword of the original function, but will return a new function and will not be called immediately.
    • Both call and apply can call the original function immediately
  • The parameters passed are different:
    • bind and call pass in a set of parameters
    • apply passes in array parameters

7. Object (obj.)

function func() {
    
    
  console.log(this.x)
}

obj = {
    
     x: 1 }
obj.func = func
obj.func() // 1
  • The function is assigned to the object, and this currently points to obj
  • If it is an arrow function, an error will be reported

8. Global this points to

function fn1 () {
    
    
    console.log(this);
}

fn1() //window对象

9. Not in the function

Scenarios that are not in functions can be divided into script tags in browsers or module files in Node.js.

  1. In the script tag, this points to Window.
  2. In the Node.js module file, this points to the default export object of the Module, which is module.exports.

Guess you like

Origin blog.csdn.net/qq_53673551/article/details/133279464