class Elemento
{
constructor (numerito)
{
this.numero = document.getElementById(numerito).innerText
this.boton = document.getElementById(numerito)
}
escribir()
{
console.log(this.numero)
}
}
numeroUno = new Elemento("1")
numeroUno.boton.addEventListener("click", numeroUno.escribir)
我试图在单击按钮时显示在控制台numerito值中,但显示“ undefined”。
[我强烈怀疑这是一个this
绑定问题-当用户单击按钮后浏览器调用事件处理程序numeroUno.escribir
时,事件处理程序numeroUno
对象已经“丢失了上下文”。
一种解决方案是使用bind
方法来修复该方法的this
引用,无论如何调用:
class Elemento
{
constructor (numerito)
{
this.numero = document.getElementById(numerito).innerText
this.boton = document.getElementById(numerito)
this.escribir = this.escribir.bind(this) // add this line
}
escribir()
{
console.log(this.numero)
}
}
您没有利用传递给构造函数的值,请尝试以下操作:
class Elemento
{
constructor (numerito)
{
this.numero = numerito // See here, use the numerito passed to the constructor function
this.boton = document.getElementById(numerito)
}
escribir()
{
console.log(this.numero)
}
}
numeroUno = new Elemento("1")
numeroUno.boton.addEventListener("click", numeroUno.escribir)
可以通过将类中的明确绑定函数]到this来解决问题。
绑定语法是:
功能名称= this.function_name.bind(this)
这里是有效的解决方案:
<html>
<head>
<title>demo</title>
</head>
<body>
<div>
<button id="1">Numerito</button>
</div>
<script>
class Elemento {
constructor (numerito) {
this.numero = document.getElementById(numerito).innerText
this.boton = document.getElementById(numerito)
}
escribir() {
console.log("numero = " + this.numero)
}
// JavaScript expects an explicit binding of each function in the class
//
// Binding syntax is:
//
// function_name = this.function_name.bind(this)
escribir = this.escribir.bind(this)
}
numeroUno = new Elemento("1")
numeroUno.boton.addEventListener("click", numeroUno.escribir)
</script>
</body>
</html>