The usage of "this" keyword in JavaScript - 07

As a Global object:

Alone, this refers to the global object.









As a Global object in a function:


function person() {
console.log(this)
}
person();
Result:





Use this in a function with strict mode:

When we use this keyword inside a function with strict mode, then it will return undefined.


function person() {
    "use strict";
    console.log(this)
}
person();

// Result: undefined


Use this with an event:

In an event, this refers to an element that receives an event.



const btn = document.querySelector("#btnClick"); console.log(btn);

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

btn.addEventListener("click", handleBtn);


Methods like call(), bind(), and apply() can refer “this” to any object.


Post a Comment

Previous Post Next Post