跳到主要内容

JavaScript 中的 this 关键字

提示
  1. 全局和函数作用域中的this:在全局作用域中,this引用全局对象(在浏览器中是window对象)。在函数内部,this同样引用全局对象。
  2. 构造函数和对象方法中的this:在构造函数中,this指向新创建的对象。在对象的方法中,this指向该方法所属的对象。
  3. 箭头函数和严格模式中的this:箭头函数中的this继承自父作用域。在严格模式的函数中,this的值是undefined,除非通过call()apply()明确设置。

在 JavaScript 中,this 关键字指的是调用它的对象。

1. 全局范围内的 this

当单独使用 this 时,this 指的是全局对象(在浏览器中是 window 对象)。例如,

let a = this;
console.log(a); // Window {}

this.name = "Sarah";
console.log(window.name); // Sarah

这里,this.namewindow.name 是相同的。

2. 函数内的 this

this 用于函数中时,this 指的是全局对象(在浏览器中是 window 对象)。例如,

function greet() {
// 函数内的 this
// this 指的是全局对象
console.log(this);
}

greet(); // Window {}

3. 构造函数内的 this

在 JavaScript 中,构造函数用于创建对象。当函数作为构造函数使用时,this 指的是使用它的对象。例如,

function Person() {
this.name = "Jack";
console.log(this);
}

let person1 = new Person();
console.log(person1.name);

输出

Person {name: "Jack"}
Jack

这里,this 指的是 person1 对象。这就是为什么 person1.name 给出了 Jack。

注意:当 thisES6 类一起使用时,它指的是使用它的对象(类似于构造函数)。

4. 对象方法中的 this

this 在对象的方法内使用时,this 指的是它所在的对象。例如,

const person = {
name: "Jack",
age: 25,

// 方法内的 this
// this 指的是对象本身
greet() {
console.log(this);
console.log(this.name);
},
};

person.greet();

输出

{name: "Jack", age: 25, greet: ƒ}
Jack

在上述示例中,this 指的是 person 对象。

5. 方法内部函数中的 this

当你在方法内部函数(在方法内)访问 this 时,this 指的是全局对象。例如,

const person = {
name: "Jack",
age: 25,

// 方法内的 this
// this 指的是对象本身
greet() {
console.log(this); // {name: "Jack", age ...}
console.log(this.age); // 25

// 内部函数
function innerFunc() {
// this 指的是全局对象
console.log(this); // Window { ... }
console.log(this.age); // undefined
}

innerFunc();
},
};

person.greet();

输出

{name: "Jack", age: 25, greet: ƒ}
25
Window {}
undefined

这里,innerFunc() 内部的 this 指的是全局对象,因为 innerFunc() 位于方法内。

然而,innerFunc() 外部的 this.age 指的是 person 对象。

6. 箭头函数中的 this

在箭头函数内部,this 指的是父作用域。例如,

const greet = () => {
console.log(this);
};
greet(); // Window {...}

箭头函数没有自己的 this。当你在箭头函数内使用 this 时,this 指的是其父作用域对象。例如,

const greet = {
name: "Jack",

// 方法
sayHi() {
let hi = () => console.log(this.name);
hi();
},
};

greet.sayHi(); // Jack

这里,hi() 函数内的 this.name 指的是 greet 对象。

你也可以使用箭头函数来解决在方法内使用函数时出现的 undefined 问题(如示例 5 中所见)。例如,

const person = {
name: "Jack",
age: 25,

// 方法内的 this
// this 指的是对象本身
greet() {
console.log(this);
console.log(this.age);

// 内部函数
let innerFunc = () => {
// this 指的是全局对象
console.log(this);
console.log(this.age);
};

innerFunc();
},
};

person.greet();

输出

{name: "Jack", age: 25, greet: ƒ}
25
{name: "Jack", age: 25, greet: ƒ}
25

这里,innerFunc() 是使用箭头函数定义的。它从其父作用域获取 this。因此,this.age 给出了 25

当箭头函数与 this 一起使用时,它指的是外部作用域。

7. 严格模式下函数内的 this

当在严格模式下的函数中使用 this 时,thisundefined。例如,

"use strict";
this.name = "Jack";
function greet() {
// this 指的是 undefined
console.log(this);
}
greet(); // undefined

注意:在严格模式下的函数内使用 this 时,你可以使用 JavaScript 函数 call()

例如,

"use strict";
this.name = "Jack";

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

greet.call(this); // Jack

当你使用 call() 函数传递 this 时,greet() 被视为 this 对象(在这种情况下是全局对象)的方法。