JavaScript 中的 this 关键词
示例
const person = {
firstName: "John",
lastName : "Doe",
id : 5566,
fullName : function() {
return this.firstName + " " + this.lastName;
}
};
自己动手试一试 »
什么是 this?
在 JavaScript 中,this
关键词指向一个对象。
this
关键词指向不同的对象,具体取决于它的使用方式。
在对象方法中,this 指向对象。 |
单独使用时,this 指向全局对象。 |
在函数中,this 指向全局对象。 |
在严格模式下的函数中,this 是 undefined 。 |
在事件中,this 指向接收事件的元素。 |
诸如 call() 、apply() 和 bind() 等方法可以将 this 指向任何对象。 |
注意
this
不是一个变量。它是一个关键词。你不能改变 this
的值。
方法中的 this
当在对象方法中使用时,this
指向对象。
在本页顶部的例子中,this
指向 person 对象。
因为 fullName 方法是 person 对象的一个方法。
fullName : function() {
return this.firstName + " " + this.lastName;
}
自己动手试一试 »
单独使用 this
当单独使用时,this
指向全局对象。
因为 this
在全局作用域中运行。
在浏览器窗口中,全局对象是 [object Window]
在严格模式下,当单独使用时,this
也指向全局对象
函数中的 this(默认)
在函数中,全局对象是 this
的默认绑定。
在浏览器窗口中,全局对象是 [object Window]
函数中的 this(严格模式)
JavaScript 严格模式不允许默认绑定。
因此,当在严格模式下的函数中使用时,this
是 undefined
。
事件处理程序中的 this
在 HTML 事件处理程序中,this
指向接收事件的 HTML 元素。
对象方法绑定
在这些例子中,this
是 person 对象
示例
const person = {
firstName : "John",
lastName : "Doe",
id : 5566,
myFunction : function() {
return this;
}
};
自己动手试一试 »
示例
const person = {
firstName: "John",
lastName : "Doe",
id : 5566,
fullName : function() {
return this.firstName + " " + this.lastName;
}
};
自己动手试一试 »
即 this.firstName 是 this(person 对象)的 firstName 属性。
显式函数绑定
call()
和 apply()
方法是预定义的 JavaScript 方法。
它们都可以用于以另一个对象作为参数调用对象方法。
下面的例子用 person2 作为参数调用 person1.fullName,this 指向 person2,即使 fullName 是 person1 的一个方法。
示例
const person1 = {
fullName: function() {
return this.firstName + " " + this.lastName;
}
}
const person2 = {
firstName:"John",
lastName: "Doe",
}
// 返回 "John Doe"
person1.fullName.call(person2);
函数借用
通过 bind()
方法,一个对象可以借用另一个对象的方法。
这个例子创建了 2 个对象(person 和 member)。
member 对象借用了 person 对象的 fullname 方法
示例
const person = {
firstName:"John",
lastName: "Doe",
fullName: function () {
return this.firstName + " " + this.lastName;
}
}
const member = {
firstName:"Hege",
lastName: "Nilsen",
}
let fullName = person.fullName.bind(member);
自己动手试一试 »
this 优先级
要确定 this
指向哪个对象;请使用以下优先级顺序。
优先级 | 对象 |
1 | bind() |
2 | apply() 和 call() |
3 | 对象方法 |
4 | 全局作用域 |
函数中的 this
是否使用 bind() 调用?
函数中的 this
是否使用 apply() 调用?
函数中的 this
是否使用 call() 调用?
函数中的 this
是否在对象函数(方法)中?
函数中的 this
是否在全局作用域中。