返回

JavaScript this 指向问题及改变 this 指向方法,严格模式,模块规范

前端

JavaScript this 指向问题

一、概述

JavaScript 中的 this 指向当前执行的函数内部的对象,其行为很像 Java 和 C++ 中的 this 指针。但与 Java 和 C++ 不同的是,JavaScript 语言是一种动态类型语言,this 的值并不是在编译时确定,而是在运行时确定。

二、规则

this 的值是由以下规则决定的:

  • 当一个函数作为对象的方法调用时,this 的值是调用该方法的对象。
  • 当一个函数作为构造函数调用时,this 的值是使用该构造函数创建的对象。
  • 当一个函数作为普通函数调用时,this 的值是全局对象。

改变 this 指向方法

一、bind() 方法

bind() 方法可以改变函数的 this 指向。语法如下:

Function.prototype.bind(thisArg, ...arg1, ...arg2, ...)

参数:

  • thisArg:指定函数的 this 指向。
  • arg1, arg2, ...: 作为函数参数传递给函数。
const person = {
  name: 'John',
  greet: function() {
    console.log(`Hello, my name is ${this.name}`);
  }
};

const greet = person.greet;
greet(); // TypeError: Cannot read property 'name' of undefined

const boundGreet = greet.bind(person);
boundGreet(); // Hello, my name is John

二、call() 方法

call() 方法也可以改变函数的 this 指向。语法如下:

Function.prototype.call(thisArg, arg1, arg2, ...)

参数:

  • thisArg:指定函数的 this 指向。
  • arg1, arg2, ...: 作为函数参数传递给函数。
const person = {
  name: 'John',
  greet: function() {
    console.log(`Hello, my name is ${this.name}`);
  }
};

const greet = person.greet;
greet.call(person); // Hello, my name is John

三、apply() 方法

apply() 方法与 call() 方法类似,唯一的区别是 apply() 方法的第二个参数是一个数组,而不是一个逗号分隔的参数列表。

const person = {
  name: 'John',
  greet: function() {
    console.log(`Hello, my name is ${this.name}`);
  }
};

const greet = person.greet;
greet.apply(person, ['Mary']); // Hello, my name is Mary

严格模式

在严格模式下,this 的值永远不会是全局对象。如果一个函数在严格模式下被调用,而 this 的值没有被显式指定,那么 this 的值将是 undefined。

模块规范

在模块规范中,this 的值是模块的作用域。这意味着在一个模块中定义的函数的 this 指向永远不会是另一个模块的作用域。

总结

本文介绍了 JavaScript 中的 this 指向问题,以及改变 this 指向的几种方法。此外,还介绍了严格模式和模块规范对 this 指向的影响。希望本文能帮助您更好地理解 JavaScript 中的 this 指向问题。