I am building a counter example using an object just for practice and ran into a problem. I am trying to update an object property using a created method within my object method. I can get it to work when I declare the objects name and increment the property's value, but if I try to use the this
keyword to represent the object my problem returns NaN
. I think I know why without fully understanding. Can anyone help me to understand?
Example that works:
let counter = {
num: 0,
increase(){
counter.num++;
document.querySelector("#value").textContent = counter.num;
},
decrease(){
counter.num--;
document.querySelector("#value").textContent = counter.num;
},
reset(){
counter.num = 0;
document.querySelector("#value").textContent = counter.num;
}
}
let x = document.querySelectorAll("button");
x[0].addEventListener("click", counter.increase);
x[1].addEventListener("click", counter.decrease);
x[2].addEventListener("click", counter.reset);
<div class="container">
<div class="display">
<h2>Counter</h2>
<br>
<span id="value">0</span>
</div>
<div class="btn-container">
<button id="increase">Increase</button>
<button id="decrease">Decrease</button>
<button id="reset">Reset</button>
</div>
</div>
Example that doesn't work:
let counter = {
num: 0,
increase(){
this.num++;
document.querySelector("#value").textContent = this.num;
},
decrease(){
this.num--;
document.querySelector("#value").textContent = this.num;
},
reset(){
this.num = 0;
document.querySelector("#value").textContent = this.num;
}
}
let x = document.querySelectorAll("button");
x[0].addEventListener("click", counter.increase);
x[1].addEventListener("click", counter.decrease);
x[2].addEventListener("click", counter.reset);
<div class="container">
<div class="display">
<h2>Counter</h2>
<br>
<span id="value">0</span>
</div>
<div class="btn-container">
<button id="increase">Increase</button>
<button id="decrease">Decrease</button>
<button id="reset">Reset</button>
</div>
</div>
Shouldn't the this
keyword point to the object (counter) making this example equivalent to the one that works?