0

I am playing around with ES6 and get stuck in "this". I have button and I want when a user click on button the text of button should be updated as "Passed".

HTML

<button type='button'>Click Me</button>

JS

class Test {
  constructor(){
    this.result = "Passed";
  }

  run() {
    alert('clicked');
    this.textContent = test.result;
  }

  btnClik() {
     document.querySelector('button').addEventListener('click', this.run ,false)
  }
}

let obj = new Test();
obj.btnClik();

You may see it in action: JSfiddle link

kp singh
  • 1,305
  • 7
  • 20
  • You haven't really specified what the issue is, but likely you're looking for: [How to access the correct `this` inside a callback?](https://stackoverflow.com/q/20279484/476) – deceze Jan 31 '18 at 09:08
  • [How does the "this" keyword work?](https://stackoverflow.com/questions/3127429/how-does-the-this-keyword-work) – Andreas Jan 31 '18 at 09:09
  • I updated your fiddle, have a look at it – VinoPravin Jan 31 '18 at 09:12

1 Answers1

1

There are a couple of mistakes

  • bind this context to the event handler
  • set textContent of event.target instead of this

i.e.

  run(event) {
    event.target.textContent = this.result; //set target of event.target
  }

  btnClik() {
     document.querySelector('button').addEventListener('click', this.run.bind( this ) ,false); //notice bind this
  }

Demo

class Test {
  constructor(){
    this.result = "Passed";
  }

  run(event) {
    event.target.textContent = this.result; //set target of event.target
  }

  btnClik() {
     document.querySelector('button').addEventListener('click', this.run.bind( this ) ,false); //notice bind this
  }
}

let obj = new Test();
console.log(obj);
obj.btnClik();
<button type='button'>Click Me</button>
gurvinder372
  • 61,170
  • 7
  • 61
  • 75