Objects with Methods and 'this'

What is 'this'?

In JavaScript, this refers to the object that is currently executing the code. When used inside a method of an object, this refers to the object itself. This allows methods to access and manipulate the object's properties.

Instructions

  1. Create an object named person with properties firstName and lastName.
  2. Add a method named getFullName to the person object that returns the full name by combining firstName and lastName.
  3. Use the this keyword inside the getFullName method to access the object's properties.
  4. Display the full name in the output div.

Example:

            
const person = {
    firstName: 'John',
    lastName: 'Doe',
    getFullName: function() {
        return this.firstName + ' ' + this.lastName;
    }
};
                  
        

References:


Open the console to see the output.