JS Object Methods

Overview

Object methods in JavaScript are functions associated with objects. They allow objects to encapsulate behavior and provide a way to perform actions related to the object's data.


Creating Object Methods

Methods can be added to objects during object creation or afterward.

1. Object Literal
Try yourself
        
            let person = {
    firstName: "John",
    lastName: "Doe",
    fullName: function() {
        return this.firstName + " " + this.lastName;
    }
};

        
    
2. Constructor Function
Try yourself
        
            function Person(firstName, lastName) {
    this.firstName = firstName;
    this.lastName = lastName;
    this.fullName = function() {
        return this.firstName + " " + this.lastName;
    };
}
let person = new Person("John", "Doe");

        
    

Invoking Object Methods

Object methods are invoked using dot notation.

Try yourself
        
            function Person(firstName, lastName) {
    this.firstName = firstName;
    this.lastName = lastName;
    this.fullName = function() {
        return this.firstName + " " + this.lastName;
    };
}
let person = new Person("John", "Doe");

let fullName = person.fullName();
console.log(fullName);   // John Doe
        
    

this Keyword

Inside an object method, the this keyword refers to the object that the method belongs to. It allows you to access the object's properties and other methods.

Try yourself
        
            let person = {
    firstName: "John",
    lastName: "Doe",
    greet: function() {
        console.log("Hello, " + this.firstName + "!");
    }
};
person.greet();   // Outputs: Hello, John!

        
    

Arrow Functions and this

Arrow functions don't have their own this. They inherit this from the surrounding scope.

Try yourself
        
            let person = {
    firstName: "John",
    sayHello: () => {
        console.log("Hello, " + this.firstName + "!");  // 'this' is undefined
    }
};
person.sayHello();   // Outputs: Hello, undefined!

        
    

Prototype Methods

Methods can also be added to an object's prototype, making them available to all instances of the object.

Try yourself
        
            function Person(firstName, lastName) {
    this.firstName = firstName;
    this.lastName = lastName;
}

Person.prototype.fullName = function() {
    return this.firstName + " " + this.lastName;
};

// Create instances of Person
const person1 = new Person("John", "Doe");
const person2 = new Person("Jane", "Smith");

// Call the fullName method on the instances
console.log(person1.fullName()); // Output: "John Doe"
console.log(person2.fullName()); // Output: "Jane Smith"
        
    

Summary

Object methods allow objects to encapsulate behavior, making them more than just data containers. They enable objects to perform actions and provide functionality.