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);

Try it yourself

保留 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();

Try it yourself

当函数用作回调时,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);

Try it yourself

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);

Try it yourself

What is this?

in JavaScript,this keyword referenceobject.

referencedwhichthe object depends on the way it is called (used or invoked).

depending on its usage, the keyword this referencing different objects:

  • in the object method,this referencing thisobject.
  • used alone,this referencedglobal object.
  • in the function,this referencedglobal object.
  • in the function, in strict mode,this is undefined.
  • in the event thatthis referenced to receive eventselements.
  • call(), apply(), and bind() methods can be used to this referenced toany object.

Note:this is not a variable. It is a keyword. You cannot modify it this .

See also:

Tutorial:JavaScript this