this can be a confusing topic for a lot of us when it comes to JavaScript. And I am going to try to make it a bit more easier of understand and work with this in JavaScript for you.
this
Ok, lets start with this itself. In JavaScript, this is a keyword refers to the context of the code. Now, that context is defined based on what we are calling this and their execution context.
Execution Context refers to an environment in which JavaScript code is executed.
There are several ways to use this, So, let’s look at what we get when call this by itself.
console.log(this)
when we run this line of code we get the Window object as output.
Window {window: Window, self: Window, document: document, name: ”, location: Location, …}
this window object contains our window methods. We get this as output because in this case context for this is global.
this in function
this when called inside a function it refers to the global object by default even though function creates it’s own execution context so,
console.log(‘this in a function’, this);
}
this_in_a_function()
Output:
Window {window: Window, self: Window, document: document, name: ”, location: Location, …}
However, if strict mode “use strict” is used it will output undefined.
this in object
When used with object we will see that this will no loger refer to Window Object.
firstName: “John”,
lastName : “Doe”,
id : 1234,
getThis : function() {
return this;
}
};
console.log(person.getThis());
We can also use this to access object properties and methods.
firstName: “John”,
lastName : “Doe”,
id : 1234,
getFullName : function() {
return this.firstName + ‘ ‘ + this.lastName;
}
};
console.log(person.getFullName());
Output:
Jhon Doe
this in arrow functions
In arrow functions, this is set lexically. That’s because the arrow function dose not make it’s own execution context but rather inherits it from outer functions.
Generally it will mean that this also refers to Window Object if arrow function is defined in global scope.
console.log(this_in_arrow())
Output:
Window {window: Window, self: Window, document: document, name: ”, location: Location, …}
but a more accurate example would be
name= ‘Jhon’
surname= ‘doe’
return (() => this.name)()
}
console.log(person());
Output:
Jhon
In this example this is scoped to the function person hence the output.
Let’s see what happens if we do this same thing with a objects.
firstName: ‘Jhon’,
lastName: ‘Doe’,
sayName: () => this.firstName
}
console.log(person.sayName());
Output:
undefined
We get undefined. Now, that’s because object does not have it’s own execution context.
I hope this cleared your doubts about this in JavaScript and helps you in journey to learn JavaScript.