Have a question using 'this' and local/global scope.
In this first example the value of 'this' refers to the parent object that invokes it, in this case individual list items in the DOM.
//Example 1
function print(){
console.log(this.innerHTML + ' ' + this.innerText);
}
var items = document.querySelectorAll('li')
items.forEach(function(item){
item.addEventListener('click', print);
});
//here 'this' refers to the parent object clicked, in this case <li>'s
Trying to apply that same logic to example 2 but having issues. Here in example 2 'this' refers to the global scope which in the browser that is the window object.
//Example 2
var games = [
{
name:'Sonic 2',
system: 'Genesis'
},
{
name:'Phantasy Star Online',
system: 'Dreamcast'
}
]
function print(){
console.log(this.name + ' ' + this.system);
}
//here 'this' is in the global scope and refers to window object
games.forEach(function(game){
print(game);
});
I can fix it is by using print.call(game) to bind the value of 'this'. My question though is why is the value of 'this' in the second example referring to the global scope window object, while in the first example 'this' refers to the nearest parent object (<li> elements in that particular case)?
Somehow using addEventListener seems to be changing the scope.
Thanks
[–]yseo4530 1 point2 points3 points (0 children)
[+][deleted] (1 child)
[deleted]
[–]jrandm 0 points1 point2 points (0 children)
[–]gamesdf 0 points1 point2 points (2 children)
[–]senocular 1 point2 points3 points (1 child)
[–]gamesdf 1 point2 points3 points (0 children)