点击按钮时控制台输出undefined的JavaScript类方法绑定问题
undefined Log in Your Click Handler Hey there! The issue you're running into is all about how JavaScript binds this in function callbacks. Let's break it down and fix it.
Why You're Seeing undefined
When you pass numeroUno.escribir directly to addEventListener, the function loses its original this binding (which should point to your Elemento instance). Instead, when the button is clicked, this inside the escribir method refers to the button DOM element itself. Since the button doesn't have a numero property, you get undefined in the console.
Three Simple Solutions
1. Wrap the Method Call in an Arrow Function
Arrow functions inherit the this value from their surrounding context (in this case, the numeroUno instance). Just update your event listener line:
numeroUno.boton.addEventListener("click", () => numeroUno.escribir())
This ensures this inside escribir stays pointed to your Elemento object.
2. Bind this in the Constructor
You can explicitly bind the escribir method to your instance in the constructor, so it always references the right this:
class Elemento { constructor(numerito) { this.numero = document.getElementById(numerito).innerText this.boton = document.getElementById(numerito) // Bind the method to the instance this.escribir = this.escribir.bind(this) } escribir() { console.log(this.numero) } } numeroUno = new Elemento("1") numeroUno.boton.addEventListener("click", numeroUno.escribir)
Now when you pass numeroUno.escribir to the listener, this will always be your Elemento instance.
3. Use an Arrow Function for the Class Method
If your environment supports class fields (modern browsers or a transpiler like Babel), you can define the method as an arrow function directly in the class. This automatically binds this to the instance:
class Elemento { constructor(numerito) { this.numero = document.getElementById(numerito).innerText this.boton = document.getElementById(numerito) } // Arrow function method binds this to the instance escribir = () => { console.log(this.numero) } } numeroUno = new Elemento("1") numeroUno.boton.addEventListener("click", numeroUno.escribir)
Any of these approaches will fix the undefined issue and make your click handler log the correct number. Pick the one that fits your code style and environment best!
内容的提问来源于stack exchange,提问作者Mikewax65

