2023前端面试题-前端Js面试题-this 的指向有几种方式及使用场景

302 阅读1分钟

在 JavaScript 中,this 是一个关键字,指向当前执行环境的上下文对象。它的指向有多种方式,可以根据不同的使用场景来选择合适的方式。

一、全局上下文中的 this

在全局作用域中,this 指向全局对象,在浏览器中就是 window 对象,在 Node.js 中则是 global 对象。

二、函数中的 this

函数的 this 指向取决于它的调用方式,常见的有以下几种情况:

作为对象的方法调用,this 指向该对象

const obj = {
  name: 'Tom',
  sayName() {
    console.log(this.name);
  }
};

obj.sayName(); // 'Tom'

作为普通函数调用,this 指向全局对象(非严格模式)或 undefined(严格模式)

function sayName() {
  console.log(this.name);
}

sayName(); // undefined (in strict mode) or window.name

使用 call、apply 或 bind 改变 this 的指向

function sayName() {
  console.log(this.name);
}

const person = { name: 'Tom' };

sayName.call(person); // 'Tom'
sayName.apply(person); // 'Tom'

const newFunc = sayName.bind(person);
newFunc(); // 'Tom'

三、构造函数中的 this

当使用 new 关键字调用函数时,会创建一个新的对象,并将构造函数中的 this 绑定到该对象上。

function Person(name) {
  this.name = name;
}

const person = new Person('Tom');
console.log(person.name); // 'Tom'

四、箭头函数中的 this

箭头函数的 this 指向取决于它在哪个上下文中被定义,而不是它在哪个上下文中被调用。通常情况下,箭头函数中的 this 会继承自它外部函数的 this。

const obj = {
  name: 'Tom',
  sayName() {
    const func = () => {
      console.log(this.name);
    };
    func();
  }
};

obj.sayName(); // 'Tom'

在选择合适的方式时,需要根据具体情况进行分析,尽可能避免 this 的指向混乱导致的问题。
更多前端面试题请看:存图,扫

daan-s.png