“this” in Javascript

Here we are going to discuss about the thisin JavaScript. this keyword behaves differently in different context.

In object method,thisis the object that is executing the current function. Below example, thiswill be the person object itself.

let person = {
name:"Aravind",
calcualteAge:function(){
console.log(this);
}
}

In regular function, this will be the window object.

function calculateAge(){
console.log(this);
}

So here is the thumb rule for thisif a function is a part of a object, that means a method in object, then the thisrefers to the object that is executing the current function. If the function is regular one and not a part of an object, then the this will be window object.

In Callback function in a method of an object, this will behave differently.

let person = {
name:"Aravind",
calcualteAge:function(){
console.log("First"+this);
setTimeout(function(){
console.log("Second"+this);
},2000)
}
}

Here the first one will be person object and the second one will the window object since the setTimeout function is a regular function and not a method in the person object. Instead of regular function, we can use arrow function to fix the context of thisto the object itself.

In Constructor and Prototypes , this is bound to the new object being constructed. when we use the new keyword, an empty object is created and thiswill be pointing to that.

function  Person(name){
this.name = name;
console.log(this);
}
let person = new Person('Aravind');
Person.prototype.calcAge = function(){
console.log(this);
}

In strict mode, however, the value of this remains at whatever it was set to when entering the execution context, so if its not set then, this will default to undefined

In call(), apply() and bind() functions, thisbehaves differently. To pass the value of this from one context to another, use call / apply.

var obj = {a: 'Custom'};

var a = 'Global';

function whatsThis() {
return this.a;
}

whatsThis(); // 'Global'
whatsThis.call(obj); // 'Custom'
whatsThis.apply(obj); // 'Custom'

bind is a brother of call and apply. The difference between bind and call/apply is that both call and apply will actually invoke the function. bind, on the other hand, returns a new function.

function f() {
return this.a;
}

var g = f.bind({a: 'Aravind'});
console.log(g()); // Aravind

Thanks to MDN and Mosh for making me understand all this

A <>er

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store