0

I consoled out the this keyword (pls refer the code) but for div the console out was different and for Input tag it's different. Wondering why?

(function(){
    document.addEventListener('DOMContentLoaded', function(){
    const complement = new Complement();
    complement.generateRandomNumber();
    complement.events();
});

class Complement{
    constructor(){
        this.firstInt = document.getElementById('firstint') //this is div
        this.secondInt = document.getElementById('secondint') //this is input
        this.sumInt = document.getElementById('sumint')
    }

    events = function(){
        this.secondInt.addEventListener('keyup', this.checkFields)


    }
}
Complement.prototype.generateRandomNumber = function(){
    **console.log(this) //this refers to the Class Complement. why?**
    let randonFirstInt = Math.floor(Math.random()*100)
    
    //assign random number to first integer
    this.firstInt.textContent = randonFirstInt;
}

Complement.prototype.checkFields = function() {
    **console.log(this) //this refers to the input tag. why?** 
    let secondIntInput = this.value
    console.log(secondIntInput)
}

})()

codejs
  • 141
  • 1
  • 10
  • `checkFields` is called as a callback from an event listener, `generateRandomNumber` is called directly via the object instance. Therefore they have different `this` contexts – UnholySheep Sep 09 '21 at 18:22
  • _`console.log(this) //this refers to the Class Complement. why?`_ — Because you’re calling `complement.generateRandomNumber();`. _`console.log(this) //this refers to the input tag. why?`_ — Because `addEventListener` will call `this.checkFields` with that particular `this` binding. – Sebastian Simon Sep 09 '21 at 18:24
  • 1
    Aside from the question itself, you are mixing `class` syntax with constructor, instance properties, and direct prototype assignment. This makes your code even more hard to reason about what `this` will actually be. `events` method can go to prototype, `checkFields` should be an arrow function declared as instance property. – Yury Tarabanko Sep 09 '21 at 18:29
  • hmmm... new to Classes & Objects. Thanks for the inputs. – codejs Sep 09 '21 at 18:34

0 Answers0