JavaScript Function 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 秒后尝试显示 person 名称,但会显示 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 秒后显示 person 名称
示例
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 指向全局对象。 |
在严格模式下的函数中,this 是 undefined 。 |
在事件中,this 指向接收事件的元素。 |
诸如 call() 、apply() 和 bind() 等方法可以将 this 指向任何对象。 |