JavaScript Function bind()
- Página anterior Aplicar JS Function
- Página siguiente Cierres de JavaScript
函数借用(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);
¿Qué es this?
en JavaScript,this
palabra clave de referenciaobjeto.
se refiere acuálel objeto depende de la forma en que se llama (usa o llama).
dependiendo de su uso, la palabra clave this
se refiere a diferentes objetos:
- en los métodos del objeto,
this
se refiere aobjeto. - al usarlo solo,
this
se refiere aobjeto global. - en la función,
this
se refiere aobjeto global. - en la función, en modo estricto,
this
esundefined
. - en el evento
this
se refiere al elemento que recibe el eventoelemento. - los métodos como call(), apply() y bind() pueden
this
se refiere aCualquier objeto.
Nota:this
No es una variable. Es una palabra clave. No puede modificarla this
.
Vea también:
Tutoriales:JavaScript this
- Página anterior Aplicar JS Function
- Página siguiente Cierres de JavaScript