JS Crumbs —Questions around ‘this’ keyword in JavaScript
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 😅
- As the value of this depends on the context, so this in global context would refer to the window object.
- 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. - Same as 2.
- Same as 2.
- While creating an object from a constructor function, this refers to the newly created object.
- Same as 2.
- 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?
❓ - Same as 6.
Extras 🌻
- What will be your answers if I put
‘use strict’;
at the top? 😛 - Fun fact: ES5 introduced the
bind()
method to set the value of a function'sthis
regardless of how it's called, and ES2015 introduced arrow functions which don't provide their ownthis
binding (it retains thethis
value of the enclosing lexical context).
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?