A brief post on `this` keyword

A brief post on `this` keyword

·

2 min read

The JavaScript this keyword refers to the object where it is used in. It's as if you could open your body, touch and move your organs kinda like. But instead of you doing this weird thing, the object does it on itself. (poor object .. ;/)

const iamObject = {
    liver: [`cell`, 'cell'],
    brain: [`coding`, 'coding'], 
    touchLiver: function() {
        console.log(this); 
        console.log(iamObject); 
    }
}
console.log( iamObject.touchLiver() ); 
// result: The iamObject gets printed twice
// conclusion: The this keyword in this particular case refers to iamObject (the one it is used in).

Trick

How we define a variable in the global scope from within a function (local scope).

console.log(globalvar) // error
function try () {
    this.globalvar = 'I am a normal variable'; 
    console.log(this); 
}
try(); // we could've used an iffy too.
console.log(globalvar) // 'I am a normal variable'

// Access the exact element which triggered event
let elements; 
elements = document.getElementsByClassName('btn'); 
Array.from(elements).forEach(function(element) {
    element.addEventListener('click', function ({
        console.log(this)
        // logs the exact HTML element that was clicked
    })); 
});

Instead of learning 10 different use cases and scenarios with the 'this' keyword (as most tutorials suggest) do it more flexible way using console logs. Just every time before using the keyword, log it in the console to ensure you're working with the correct object. Over time you will get the feeling of how it works and eventually you won't need to log in anymore.

Thanks for Reading🤩

Did you find this article valuable?

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