0

What would be the correct way to reference "this.target" from within the function that is attached to an event.

Its a simple question I know, I have tried to search for answers here but my lack of knowledge is hampering me finding answers that are directly related to this problem.

    function ChangeBgCol(target,color){
        this.target = target;
        this.color = color;
        this.changeCol = function(){ 
            document.getElementById("button").addEventListener("click",function(){
                document.getElementById(this.target).style.backgroundColor = this.color;   
            });
        }
    }

    var change = new ChangeBgCol("tar1","red");
    change.changeCol();
.divStyle{
    width: 50px;
    height: 50px;
    background-color: black;
  <div class="divStyle" id="tar1"></div>
  <div class="divStyle" id="tar2"></div>
  <button id="button">press</button>
Darth Den
  • 1
  • 2

2 Answers2

0

Since .changeCol is a function, you need to either bound it to the constructor or you need to use an arrow function. Basically, as soon as you enter that nested function, you lose all lexical binding the to parent function.

this.changeCol = this.changeCol.bind(this);

or

this.changeCol = () => {}

this in Javascript is a little weird, you can read up on it in the Moz docs. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this or this incredibly popular question on SO How does the "this" keyword work?

Sean Kelly
  • 901
  • 7
  • 27
0

The context this at that moment is related to the context of the handler rather than the context of ChangeBgCol.

An alternative is directly using the params target and color.

function ChangeBgCol(target, color) {
  this.target = target;
  this.color = color;
  this.changeCol = function() {
    document.getElementById("button").addEventListener("click", function() {
      document.getElementById(target).style.backgroundColor = color;
    });
  }
}

var change = new ChangeBgCol("tar1", "red");
change.changeCol();
.divStyle {
  width: 50px;
  height: 50px;
  background-color: black;
}
<div class="divStyle" id="tar1"></div>
<div class="divStyle" id="tar2"></div>
<button id="button">press</button>

The second alternative is binding the desired context using the function bind, however, you're going to lose the context of the triggered event:

function ChangeBgCol(target, color) {
  this.target = target;
  this.color = color;

  this.changeCol = function() {
    document.getElementById("button").addEventListener("click", (function() {
      document.getElementById(this.target).style.backgroundColor = color;
    }).bind(this)/*Here is the binding logic*/);
  };
}

var change = new ChangeBgCol("tar1", "red");
change.changeCol();
.divStyle {
  width: 50px;
  height: 50px;
  background-color: black;
}
<div class="divStyle" id="tar1"></div>
<div class="divStyle" id="tar2"></div>
<button id="button">press</button>
Ele
  • 33,468
  • 7
  • 37
  • 75