[英]“undefined” shows up in console when button clicked
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)
我试图在单击按钮时在控制台中显示数字值,但它显示“未定义”。
我强烈怀疑这是一个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 来解决。
绑定语法是:
function_name = 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>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.