0

I am very new to OOP and attempting my first project with it. Here is my question:

var calculator = {
  operationBar: document.getElementById('operation-bar'),
  print: function(){
    this.operationBar.innerHTML += 1;
  }
}

var one = document.getElementById('number1');
one.addEventListener('click',calculator.print)

When I click on my HTML element with the id (number1) I get the following error:

Cannot read property 'innerHTML' of undefined.

It is not relating the this keyword to my calculator object.

However if I do this:

var calculator = {
  operationBar: document.getElementById('operation-bar'),
  print: function(num){
    this.operationBar.innerHTML += 1;
  }
}

calculator.print()

It works and the this keyword seems to be working correctly.

The reason I know the problem is with the this keyword is because if I perform the function in the first snippet and replace this with calculator then it will work, as my event handler function as well.

Why is it behaving this way?

0 Answers0