JavaScript Function bind()
- Vorige pagina JS Functie Apply
- Volgende pagina JS Closures
函数借用(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);
Wat is this?
in JavaScript,this
keyword verwijstobject.
verwijstwelkeobject hangt af van de manier van aanroep (gebruik of aanroep).
afhankelijk van de manier van gebruik, het keyword this
verwijst naar verschillende objecten:
- in objectmethoden,
this
verwijst naar ditobject. - gebruikt alleen,
this
verwijstglobale object. - in de functie,
this
verwijstglobale object. - in de functie, in strikte modus,
this
isundefined
. - in het evenement,
this
verwijst naar het object dat het evenement ontvangtelement. - call()、apply() en bind() en andere methoden kunnen
this
verwijst naarelke object.
Let op:this
is geen variabele. Het is een keyword. U kunt het niet wijzigen this
waarde.
Zie ook:
Handleiding:JavaScript this
- Vorige pagina JS Functie Apply
- Volgende pagina JS Closures