JavaScript: What the hell is ‘this’?(Part-I)

Sadique Quraishi
2 min readMay 8, 2020

--

‘this’ is keyword in JavaScript used to define the context for a piece of code that is being executed.

It is the most asked topic during the JavaScript interview. The interviewer gives some piece of code and asks the value of ‘this’, for example:

var a = `10, I am in global scope`;
var obj = {
a: `5, I am in obj’s scope.` ,
b: function () {
console.log(this.a);
function c () {
console.log(this.a);
}
c();
}
}

A lot of people will start thinking at this time about the value of ‘this’. Never do that.

The value of ‘this’ is defined at runtime, not at the declaration time.

console.log(this.a);
obj.b();
let x = obj.b;
x();
let y = obj.b.bind(obj);
y();

Now, when you get the code that shows how the user is trying to invoke the values, you can start to think about the value of ‘this’.

Let’s determine the value of ‘this’

console.log(this.a);
// output: "10, I am in global scope"

the code is being executed in the context of the window’s object and at this moment ‘this’ refers to windows object.

obj.b();
// output:
// "5, I am in obj's scope."
// "10, I am in global scope"

Here, the method is called with dot(.) notation. The context for method ‘b()’ has been set to obj and thus, ‘this’ refers to ‘obj’ object.

After the execution of ‘console.log’ in obj.b, method c() will be executed and for c(), no context is defined explicitly, thus it will execute in window’s context and output is “10, I am in global scope”.

let x = obj.b;
x();
// output:
// "10, I am in global scope"
// "10, I am in global scope"

In this case, x refers to the method b defined in obj, but it has been executed within the window’s context, so ‘this’ refers to windows object. For the execution of c(), it remains the same as explained above.

let y = obj.b.bind(obj);
y();
// output:
// "5, I am in obj's scope."
// "10, I am in global scope"

In this case, y refers to a new method that is created by binding obj.b in the context of obj, so ‘this’ refers to ‘obj’ object. For the execution of c(), it remains the same as explained above.

This is to describe the behavior of ‘this’ keyword with respect to function calls. The behavior also changes in case of arrow(=>) functions and Classes which will be covered in future posts.

--

--