DEV Community

loading...
Cover image for You don't know 'this' in JavaScript

You don't know 'this' in JavaScript

rahxuls profile image Rahul ・1 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'
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode
  • 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😎

Discussion (1)

pic
Editor guide
Collapse
programmerno24 profile image
Darsh

No bro i know about it and it is true i saw some one use this in his project in khan academy you can get link to my khan academy profile in my dev profile