JavaScript bind() 函数方法
函数借用
通过 bind() 方法,一个对象可以从另一个对象借用一个方法。
以下示例创建了两个对象(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
有时需要使用 bind() 方法来防止丢失 this。
在下面的示例中,person 对象有一个 display 方法。在 display 方法中,this 指的是 person 对象:
示例
const person = {
firstName:"John",
lastName: "Doe",
display: function () {
let x = document.getElementById("demo");
x.innerHTML = this.firstName + " " + this.lastName;
}
}
person.display();亲自试一试 »当函数用作回调函数时,this 会丢失。
此示例尝试在 3 秒后显示人名,但会显示 undefined。
示例
const person = {
firstName:"John",
lastName: "Doe",
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:"John",
lastName: "Doe",
display: function () {
let x = document.getElementById("demo");
x.innerHTML = this.firstName + " " + this.lastName;
}
}
let display = person.display.bind(person);
setTimeout(display, 3000);亲自试一试 »什么是 this?
在 JavaScript 中,this关键字指的是一个对象。
this关键字指的是不同的对象,具体取决于它的使用方式:
单独使用时,this 指的是全局对象。 |
在函数中,this 指的是全局对象。 |
在函数中,如果处于严格模式,this 的值为undefined。 |
在对象方法中,this 指的是对象。 |
在事件中,this 指的是接收该事件的元素。 |
像 call()、apply() 和 bind() 这样的方法可以将 this 指向任何对象。 |
注意
this 不是一个变量。
this 是一个关键字。
您无法更改 this 的值。
