this in the Global Context

Marius Schulz
InstructorMarius Schulz
Share this video with your friends

Social Share Links

Send Tweet
Published 6 years ago
Updated 5 years ago

JavaScript's this mechanism behaves a little differently compared to other languages. When used in the global context (outside of any function), this refers to the global object. This lesson highlights the different behavior between Node and the browser.

Instructor: [00:01] JavaScript's this mechanism behaves a little differently compared to other languages. It might not always be intuitive. Let's start off by looking at how this works in the global execution context. When used outside of any function, this refers to the global object.

[00:18] In the browser, that would be window. It doesn't matter whether or not we are in strict mode. A top-level this always refers to the global object. Now let's switch over to node. At the top level, this is equivalent to the global object as well, which is called global.

[00:42] However, that is only true within the node REPL. Let's execute the same line of code within a node module. Suddenly, we get false. This is because, in the top-level code of a node module, this is equivalent to module.exports.

[01:09] If we now run the program again, we get true. The node engine runs each module code inside of a REPL function. That REPL function is invoked with a this value set to module.exports. In a future lesson, we are going to discuss how to invoke a function with a specific this value using either call, apply, or bind.

Tengjiao
Tengjiao
~ 6 years ago

simple but useful, thanks

Tengjiao
Tengjiao
~ 6 years ago

simple but useful, thanks

Alicia
Alicia
~ 6 years ago

Off topic, but what sort of text editor/terminal configuration is that? It looks lovely. :)

Marius Schulz
Marius Schulzinstructor
~ 6 years ago

@Alicia: I'm using Visual Studio Code with the Dracula theme. A lovely combination, indeed :)

Markdown supported.
Become a member to join the discussionEnroll Today