JavaScript Function bind()

函数借用(Function Borrowing)

通过使用 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);

亲自试一试

保留 this

有时必须使用 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);

亲自试一试

什么是 this?

在 JavaScript 中,this 关键字引用对象

引用哪个对象取决于调用(使用或调用)的方式。

根据其使用方式,关键字 this 引用不同的对象:

  • 在对象方法中,this 引用该对象
  • 单独使用时,this 引用全局对象
  • 在函数中,this 引用全局对象
  • 在函数中,在严格模式下,thisundefined
  • 在事件中,this 引用接收事件的元素
  • call()、apply() 和 bind() 等方法可以将 this 引用到任何对象

注意:this 不是变量。它是一个关键字。您无法修改 this 的值。

另请参阅:

教程:JavaScript this


http://www.vxiaotou.com