Hey guys. The "this" keyword in JavaScript can be very confusing because the creators of JavaScript made that keyword play multiple roles which could confuse a developer. In this article, I'll summarize the usages of the "this" keyword.
[1] "This" in a Method
A method is just a normal function but which is a part of an object. Any usage of "this" in a method refers to the object it is in. For example, take a look at this key-value pair:
const person = {
name: "Ishak",
birthYear: 1831,
age: function() {
return 2021 - this.birthYear;
}
}
[2] "This" as a Standalone Keyword
If you find any "this" keyword lying around in your JavaScript file, it refers to the global object (window object in browser and global in Node).
this.isALineOfCode;
[3] "This" in a Function
While methods are functions that is part of an object, a function is a standalone code. Since it is not attached to any object/parent, "this" in a function refers to global object (window object in browser and global in Node).
function doSomething() {
return this;
}
[4] "This" in Function in Strict Mode
While developers would usually prefer to use TypeScript if they want to be strict, strict mode is a great option for starters. In strict mode, if you write "this" in a function, you'll get undefined.
"use strict";
function doSomething() {
return this;
}
Top comments (0)