What is 'this' ? ๐Ÿ˜ณ

mayank0508

Mayank Kumar

Posted on August 31, 2021

What is 'this' ? ๐Ÿ˜ณ

This ๐Ÿ˜ญ

The this keyword can lead to some headaches in JavaScript - this blog hopefully acts as a remedy.

hi

this refers to different things, depending on where it's used and how (if used in a function) a function is called !

Generally, this refers to the "thing" which called a function. That can be the global context, an object or some bound data/ object (e.g. when the browser binds this to the button that triggered a click event).

1) this in Global Context (i.e. outside of any function)

function something() { ... }

console.log(this); 
Enter fullscreen mode Exit fullscreen mode

// logs global object (window in browser) - ALWAYS (also in strict mode)! ๐Ÿ™Œ

2) this in a Function (non-Arrow) - Called in the global context

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

something(); 
Enter fullscreen mode Exit fullscreen mode

// logs global object (window in browser) in non-strict mode, undefined in strict mode ๐Ÿ™Œ

3) this in an Arrow-Function - Called in the global context

const something = () => { 
    console.log(this);
}

something(); 
Enter fullscreen mode Exit fullscreen mode

// logs global object (window in browser) - ALWAYS (also in strict mode)! ๐Ÿ™Œ

4) this in a Method (non-Arrow) - Called on an object

const person = { 
    name: 'Mayank',
    greet: function() { // or use method shorthand: greet() { ... }
        console.log(this.name);
    }
};

person.greet(); 
Enter fullscreen mode Exit fullscreen mode

// logs 'Max', "this" refers to the person object ๐Ÿ™Œ

5) this in a Method (Arrow Function) - Called on an object

const person = { 
    name: 'Max',
    greet: () => {
        console.log(this.name);
    }
};

person.greet();
Enter fullscreen mode Exit fullscreen mode

// logs nothing (or some global name on window object), "this" refers to global (window) object, even in strict mode ๐Ÿ™Œ

If in doubt, a console.log(this); can always help you find out what this is referring to at the moment!

image

HAPPY CODING ๐Ÿ‘จโ€๐Ÿ’ป

๐Ÿ’– ๐Ÿ’ช ๐Ÿ™… ๐Ÿšฉ
mayank0508
Mayank Kumar

Posted on August 31, 2021

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related

ยฉ TheLazy.dev

About