LOTUSMS LOTUSMS - 13 days ago 8
Javascript Question

What does the 'this' keyword return when pointing to the window

I am taking a Javascript Bootcamp, since I never really really really learned it from the educational standpoint, but more from the practical standpoint. And as I was exploring the

this
keyword from the window object I discovered something intriguing and I would like to know what is it and how useful can this be.

So I did this

console.log(this);


And went to the console and saw, as I expected, the
this
keyword pointing to the
Window
. But when I clicked in the arrow to expand, I saw this huge list
enter image description here

What are these exactly? Is this a reference of all functions that can be interpreted by the browser? Like a library or documentation of functions available to me?

Even more intriguing was when I expanded one of these (for instance, AnimationEvent) and saw it gets deeper. See below
enter image description here

Excuse my ignorance. I am trying to learn this the right way.

EDIT to possible duplicate

This is a question related to the
this
keyword and what is returning to me from the window object. The question here is related to a click event or callback. Doesn't answer my question.

Answer

These are all the functions that are part of the window object.

Think of it this way. All functions are part of an object. 'this' in running code returns the object context that the function is running in. It may be the object that the function was defined under, but 'this' can be dynamically changed in code, so more accurately its the object context that the function is running in.

window is the global object in a browser, so when you're not inside a function that is part of a sub-object to window, you are in the window object context.

for instance,

var o = { test: function(){ alert(this) } }
o.test();

will alert the o object, not window.

You can call functions directly that are in the same context, which is why you can type Infinity in the console, and it returns Infinity which is part of window.

JavaScript will also look up parent objects (window in this case) to the declared object as well, so in your browser console, this works:

var o = { test: function(){ alert(Infinity) } }
o.test();