This Keyword in Javascript

This Keyword in Javascript

'This' keyword depends on how and where a function is called.

It acts like a chameleon, Adapting its meaning based on the context. This refers to an object that is executing the current function or code.

Inside an Object method

When 'This' is used within an object, it refers to the object itself.

const person = {
    name: 'vikas',
    greet(){
        console.log("Namste: ",this.name);
    }
}

person.greet() // Output: Namste: vikas

Standalone Function

When 'This' Used in a standalone function outside of any object or defined in the global scope. So it's usually refers to the global object.

In the Browser, 'this' refers to a global object window; in Node.js, this refers to the global object.

Event Handler

When function Used is an Event handler (like oneClick, addEventListner) so 'This' refers to the Dom Element.

<button id = "clickButton"> Click me</button>
const button = document.getElementById('clickButton');
button.addEventListner('click', function(){
    console.log('Button Clicked this:=>'. this.button) // Output: Button Clicked this:=> <button id = "clickButton"> Click me</button>
})

Explicit binding { call( ) , Apply( ), & bind( ) }

This methods allows us to manually set the value of 'this' when calling a function.

 greet(){
        console.log("Hello, My name is ",this.name);
    }

const objVariable1 = {name: 'objVariable1'}
const objVariable2 = {name: 'bjVariable2'}

greet.call(objVariable1) // output: Hello, my name is objVariable1

greet.apply(objVariable2) // output: Hello, my name is objVariable2

const boundgreet = greet.bind(objVariable2) 

boundgreet() // output: Hello, my name is objVariable2

Conclusion

'This' Goes one scope outside and checks how to resolve because this first checks the current context if he doesn't find it. It goes one step back function and sees the call side it's defined or not yes it is defined then it prints the value.