You don't know 'this' in JavaScript

You don't know 'this' in JavaScript

·

2 min read

The this keyword in JavaScript refers to the main object which it belongs to and it has different values depending on where it is used:

  • Inside a method or object this refers to the owner/current object.
  • Alone or inside a function it refers to the global object(window object in browsers).
const foo = {
    name: 'Rahul', 
    func: function() {
        return this.name; 
    }
}; 

console.log(foo.func()); // 'Rahul'

Now let's see some examples with the arrow function and normal method

const foo = {
    name: 'RAHULISM', 
    arrowfunc: _ => `Welome to "${this.name}"`, 
    fooMethod: function() {
        return `Welcome to "${this.name}"`; 
    }
}; 

console.log(foo.arrowFunc()); // Welcome to ""
console.log(foo.fooMethod()); // Welcome to RAHULISM

Here fooMethod() is a method inside the object so this refers to the current object, but for arrow function this always points to the closest function scope. Since foo is not a function so the this inside the arrowFunc() points to the global object (in browser window object).

Now let's try the same inside a function.

function foo () { 
    this.name = 'RAHULISM'; 
    const arrowFunc = _ => `Welcome to ${this.name}`; 
    function normalFunc () { 
        return `Welcome to ${this.name}`; 
    }
    return { arrowFunc, normalFunc }; 
}

console.log(foo().arrowFunc()); // Welcome to RAHULISM
console.log(foo().normalFunc()); // Welcome to undefined
  • arrowFunc(): this points to the nearest function scope and so prints 'RAHULISM'.
  • normalFunc(): this points to the global object, which does not have the property 'name' and so prints undefined.

You should make use of this.


⚡Happy Coding | Thanks For Reading😎

Did you find this article valuable?

Support Rahul by becoming a sponsor. Any amount is appreciated!