GIVEN:
var box5 = {
color: 'green',
position: 1,
clickMe: function() {
console.log{this)
}
}
The console.log = {color: "green", position: 1, clickMe: ƒ}
In other words pointing at the object "box5".
But add the following code:
document.querySelector('.green').addEventListener('click', function() {
var str = 'This is box number ' + this.position + ' and it is ' + this.color;
alert(str);
});
And you get the alert: "This is box number undefined
and it is undefined
"
Question: Why is 'this' apparently pointing at the object when I log it, not when it try to print object values with "this.property"
There is the "hack" self = this
and reference properties with self instead of this.