Reputation: 13
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)
I'm trying to show in console numerito value when button is clicked but instead it shows "undefined".
Upvotes: 1
Views: 122
Reputation: 4937
The problem can be fixed by explicitly binding the function in the class to this.
Binding syntax is:
function_name = this.function_name.bind(this)
Here is the working solution:
<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>
Upvotes: 0
Reputation: 18249
I strongly suspect this is a this
binding issue - when the event handler numeroUno.escribir
is called by the browser after the user clicks the button, it has "lost the context" of the numeroUno
object.
One solution this is to use the bind
method to fix the this
reference of the method, no matter how it is called:
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)
}
}
Upvotes: 4
Reputation: 3152
You are not utilising the value that you pass to the constructor, try this:
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)
Upvotes: 0