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