2023前端面试:一篇文章解释清楚javascript中的this

55 阅读1分钟

解释javascript中的this

JS 中的this是一个相对复杂的概念,不是简单几句能解释清楚的。因为它用于引用当前执行代码的对象。 this 可以在任何函数中使用,包括对象方法、函数、类方法等。

粗略地讲,函数的调用方式决定了this的值( ES2015 中的箭头函数将忽略),下面是一些 this 值的示例:

1. 当函数作为对象的方法调用时,this 指向该对象:

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

myObj.greet(); // 输出 "Hello, my name is John"

2. 当函数作为普通函数调用时,this 指向全局对象 window(在浏览器中)或 global(在 Node.js 中):

function myFunc() {
  console.log(this === window); // 输出 true(在浏览器中)
}

myFunc();

3. 使用 call()apply() 可以改变 this 的值:

const myObj1 = {
  name: "John"
};

const myObj2 = {
  name: "Jane"
};

function greet(a,b,c) {
  console.log(`Hello, my name is ${this.name} ${a} ${b} ${c}`);
}

greet.call(myObj1,1,2,3); // 输出 "Hello, my name is John 1 2 3"
greet.apply(myObj2,[1,2,3]); // 输出 "Hello, my name is Jane 1 2 3"

4. 当函数作为构造函数使用时,this 指向新创建的对象:

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

const john = new Person("John");
console.log(john.name); // 输出 "John"

总之,this 的值在函数调用时确定,它的值取决于函数的调用方式。

5. ES2015 中的箭头函数 this 的指向

在 JavaScript 中,箭头函数使用的 this静态作用域。这意味着箭头函数的 this 始终引用函数被定义时所处的上下文,而不是函数被调用时所处的上下文

下面是一些示例来说明箭头函数的 this

// 在全局上下文中定义一个箭头函数
const arrowFunction = () => {
  console.log(this);
};

// 调用箭头函数,输出全局对象
arrowFunction(); // Window { ... }

const obj = {
  name: "John",
  greet: () => {
    console.log(`Hello, ${this.name}!`);
  }
};

obj.greet(); // 输出 "Hello, undefined!"

在上面的例子中,arrowFunction 是在全局上下文中定义的,因此它的 this 引用全局对象。而 obj 对象的 greet 方法中使用了箭头函数,但是由于箭头函数的 this 是在定义时确定的,它引用的 thisobj.greet 方法被定义时的上下文,即全局对象,因此输出 Hello, undefined!

需要注意的是,箭头函数的 this 不能被显式地修改。即使使用 call()apply() 方法来调用箭头函数,也无法改变它的 this。如果需要在函数调用时改变 this 的值,可以使用普通的函数表达式或函数声明。