“未定义”在单击按钮时显示在控制台中

问题描述 投票:1回答:3
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”。

javascript
3个回答
4
投票

[我强烈怀疑这是一个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)
  }
}

0
投票

您没有利用传递给构造函数的值,请尝试以下操作:

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)

0
投票

可以通过将类中的明确绑定函数]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>
© www.soinside.com 2019 - 2024. All rights reserved.