在 JavaScript 中,this
关键字指的是被调用时所在的 对象。
1. 全局作用域中的 this
当 this
单独使用时,this
指的是全局对象(浏览器中的 window
对象)。例如:
let a = this;
console.log(a); // Window {}
this.name = 'Sarah';
console.log(window.name); // Sarah
在此,this.name
等同于 window.name
。
2. 函数中的 this
当 this
在函数中使用时,this
指的是全局对象(浏览器中的 window
对象)。例如:
function greet() {
// this inside function
// this refers to the global object
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。
注意:当 this
与 ES6 类一起使用时,它指的是它被使用的那个对象(类似于构造函数)。
4. 对象方法中的 this
当 this
在对象的某个方法中使用时,this
指的是它所属的对象。例如:
const person = {
name : 'Jack',
age: 25,
// this inside method
// this refers to the object itself
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 inside method
// this refers to the object itself
greet() {
console.log(this); // {name: "Jack", age ...}
console.log(this.age); // 25
// inner function
function innerFunc() {
// this refers to the global object
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
指的是它的父作用域对象。例如:
const greet = {
name: 'Jack',
// method
sayHi () {
let hi = () => console.log(this.name);
hi();
}
}
greet.sayHi(); // Jack
在此,hi()
函数中的 this.name
指的是 greet
对象。
你还可以使用箭头函数来解决在方法中使用函数时出现 undefined
的问题(如示例 5 所示)。例如:
const person = {
name : 'Jack',
age: 25,
// this inside method
// this refers to the object itself
greet() {
console.log(this);
console.log(this.age);
// inner function
let innerFunc = () => {
// this refers to the global object
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
在严格模式函数中使用时,this
为undefined。例如:
'use strict';
this.name = 'Jack';
function greet() {
// this refers to undefined
console.log(this);
}
greet(); // undefined
注意:在严格模式函数中使用 this
时,你可以使用JavaScript Function call()。
例如,
'use strict';
this.name = 'Jack';
function greet() {
console.log(this.name);
}
greet.call(this); // Jack
当你使用 call()
函数传递 this
时,greet()
被视为 this
对象(在这种情况下是全局对象)的方法。