The "this" keyword

Description

The "this" keyword in JavaScript refers to the object it belongs to. When it is used in a method, it refers to the "owner" of the method.

Example 1:

//When it is used in a method;
var person = {
    firstName: 'John',
    lastName: 'Doe',
    id: 1,
    fullName: function() { 
            return `${this.firstName} ${this.lastName}` 
        }
}
console.log(person.fullName());
//Result will be; John Doe.
//The "this" keyword in this context refers to the person object. The person object is   the owner of the fullName method.

//KEYNOTE:
//When using the "this" keyword in methods, the ES5 way of writing functions with the function keyword has to be used. If an arrow function is used like so;
var person = {
    firstName: 'John',
    lastName: 'Doe',
    id: 1,
    fullName: () => { 
            return `${this.firstName} ${this.lastName}` 
        }
}
console.log(person.fullName());
//Result will be; undefined undefined.

//Based on this, arrow functions are not suitable for object methods.

Example 2:

//When it is used alone;
var me = this;
console.log(me);
//Result will be; the Window object.

//When it is used alone, it refers to the global object. The global object in a browser  window is the Window Object.

Example 3:

//When it is used with an arrow function;
//When using arrow function, the "this" keyword is equal to whatever it was at an higher function, outside of the function it is being used. If there is no higher function, it  is equal to the window object.
var ninja = {
    name: "Ranti",
    drink(x) {
        window.setInterval(() => {
            if (x > 0) {
                console.log(this.name + " drank coffee");
                x--;
            }
        }, 1000);
    }
}
ninja.drink(5);
//Result will be; Ranti drank coffee. With a count of 5 times.

Example 4:

//When it is used in event handling
//When the "this" keyword is used in event handlers, it refers to the HTML element that  received the event. 
<button onclick="this.style.display='none'">Click Me</button>

//"this" refers to the element on the left of it.

No Comments Yet