手册
目录
通过使用 bind() 方法,一个对象可以从另一个对象借用一个方法。
下面的例子创建了 2 个对象(person 和 member)。
member 对象借用了 person 对象的 fullname 方法:
const person = {
firstName:"Bill",
lastName: "Gates",
fullName: function () {
return this.firstName + " " + this.lastName;
}
}
const member = {
firstName:"Hege",
lastName: "Nilsen",
}
let fullName = person.fullName.bind(member);
运行实例 »点击 "运行实例" 按钮查看在线实例
有时必须使用 bind() 方法来防止丢失 this。
在下面的例子中,person 对象有一个 display 方法。在 display 方法中,this 指的是 person 对象:
const person = {
firstName:"Bill",
lastName: "Gates",
display: function () {
let x = document.getElementById("demo");
x.innerHTML = this.firstName + " " + this.lastName;
}
}
person.display();
运行实例 »点击 "运行实例" 按钮查看在线实例
当函数用作回调时,this 会丢失。
这个例子将尝试在 3 秒后显示人名,但它会显示 undefined:
const person = {
firstName:"Bill",
lastName: "Gates",
display: function () {
let x = document.getElementById("demo");
x.innerHTML = this.firstName + " " + this.lastName;
}
}
setTimeout(person.display, 3000);
运行实例 »点击 "运行实例" 按钮查看在线实例
bind() 方法解决了这个问题。
在下面的例子中,bind() 方法用于将 person.display 绑定到 person。
此例将在 3 秒后显示人名:
const person = {
firstName:"Bill",
lastName: "Gates",
display: function () {
let x = document.getElementById("demo");
x.innerHTML = this.firstName + " " + this.lastName;
}
}
let display = person.display.bind(person);
setTimeout(display, 3000);
运行实例 »点击 "运行实例" 按钮查看在线实例
在 JavaScript 中,this 关键字引用对象。
引用哪个对象取决于调用(使用或调用)的方式。
根据其使用方式,关键字 this 引用不同的对象:
this 引用该对象。this 引用全局对象。this 引用全局对象。this 是 undefined。this 引用接收事件的元素。this 引用到任何对象。注意:this 不是变量。它是一个关键字。您无法修改 this 的值。
教程:JavaScript this
相关
视频
RELATED VIDEOS
科技资讯
1
2
3
4
5
6
7
8
9
精选课程
共5课时
17.2万人学习
共49课时
77万人学习
共29课时
61.7万人学习
共25课时
39.3万人学习
共43课时
70.9万人学习
共25课时
61.6万人学习
共22课时
23万人学习
共28课时
33.9万人学习
共89课时
125万人学习