JS Crumbs —Questions around ‘this’ keyword in JavaScript

Anand Suthar
2 min readJul 11, 2020

--

Photo by Greg Rakozy on Unsplash

A few words regarding ‘this’:

A function’s this keyword behaves a little differently in JavaScript compared to other languages. It also has some differences between strict mode and non-strict mode.
It’s value is a property of an execution context (global, function or eval) that, in non–strict mode, is always a reference to an object and in strict mode can be any value.

📓 Few pointers:

  • Determined by how a function is called (runtime binding) and may be different each time it is called.
  • Cannot be set by assignment.

Questions❓

  • What will be the output of following code (note them in sequential order to verify)?

[Note: Imagine this code is ran on debugger console of modern browser. Also this code is not run in strict mode.]

console.log(this)function Foo () {
console.log(this);
}
Foo();
Foo.call();
Foo.apply();
var foo = new Foo();
var bar = { name: 'Bar' };
Foo(bar);
Foo.call(bar);
Foo.apply(bar);

Check the results 😏

To avoid seeing results, I’ve posted it in this bin. You can also confirm the results by pasting code in any debugger console.

Due Explanations 😅

  1. As the value of this depends on the context, so this in global context would refer to the window object.
  2. In non-strict mode the value of this in such case will be the global object (window in a browser, we’ll get to it later in the chapter Global object). This is a historical behavior that "use strict" fixes.
  3. Same as 2.
  4. Same as 2.
  5. While creating an object from a constructor function, this refers to the newly created object.
  6. Same as 2.
  7. Call method accepts first parameter as context so if we provide an object than that becomes the context.
    What if we don’t pass the argument?
  8. Same as 6.

Extras 🌻

Arigato

Thank you for finding the time to read this story. I tried to provide some good questions and explanations. Please let me know where this can be improved. Also I am thinking of taking small topics and creating short stories (2 min read) focused on each, what should I pick next?

--

--

Anand Suthar
0 Followers

Full Stack Developer trying to understand JavaScript and Python better