1

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.

Jin
  • 1,400
  • 1
  • 9
  • 27
Godfather
  • 171
  • 1
  • 9

2 Answers2

1

Probably because this is an HtmlElement, and an HtmlElement does not have a property called position or a property called color.

this is a representation of the object that called the current function. And if an event is fired, the callback function is called by the object the event happened to. In this case, an HtmlElement.

If you'd like to get values from an html element, you can try adding them to the dataset of the element. You can use Vanilla Javascript, and jQuery has their own method implementation

bronkula
  • 536
  • 3
  • 11
0

Javascript knows to make a this value present when a function is called while simultaneously dereferencing it off of an object. If a function is called, but not simultaneously dereferenced off an object, its this value will be the global object (window, in the case of browsers).

For example, consider this object:

let obj = {
  name: 'amazing obj',
  func: function() { console.log(this); }
};

If we now say:

obj.func();

We will see the console output obj itself.

But if we say:

let func = obj.func;
func();

We will see the console output the global object.

The difference between obj.func(), and func(), is that javascript sees that in obj.func's case the function is being dereferenced off of obj, and therefore makes obj the value for this.

Gershy
  • 5,378
  • 1
  • 27
  • 38