0

I'm getting a problem where I cannot access the national variables of a Class inside the onclick function of another variable of the same Class. I have made a small demo where I assign a message and return a button which should show the message, but it keeps printing undefined because it can't find the variable. Please Help

class class1 {
  message = "";
  clicker = document.createElement("button");
  
  constructor(sentence) {
    this.message = sentence;
    this.clicker.id = "clicker";
    this.clicker.innerHTML = "CLICK ME";
    this.clicker.addEventListener("click", (function () {
        console.log(this.message);
    }).bind(this))
    return this.clicker;
  }
}

document.getElementById("content").appendChild(new class1("hello"));
<html>
<head>
  <title></title>
</head>
<body>
  <div id='content'></div>
</body>
</html>

1 Answer 1

2

The function is bound with the HTML element who triggered the event, you can either use arrow functions or bind the desired specific lexical context.

Using arrow functions.

class class1 {
  message = "";
  clicker = document.createElement("button");
  
  constructor(sentence) {
    this.message = sentence;
    this.clicker.id = "clicker";
    this.clicker.innerHTML = "CLICK ME";
    this.clicker.onclick = () => {
      console.log(this.message);
    }
    return this.clicker;
  }
}

document.getElementById("content").appendChild(new class1("hello"));
<html>
<head>
  <title></title>
</head>
<body>
  <div id='content'></div>
</body>
</html>

Binding

class class1 {
  message = "";
  clicker = document.createElement("button");
  
  constructor(sentence) {
    this.message = sentence;
    this.clicker.id = "clicker";
    this.clicker.innerHTML = "CLICK ME";
    this.clicker.onclick = (function() {
      console.log(this.message);
    }).bind(this)
    return this.clicker;
  }
}

document.getElementById("content").appendChild(new class1("hello"));
<html>
<head>
  <title></title>
</head>
<body>
  <div id='content'></div>
</body>
</html>

Sign up to request clarification or add additional context in comments.

2 Comments

how will you write this in the form of this.clicker.addEventListener("click", funtion(){});
I updated the snippet in my question, and I'm getting an error

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.