Adding a Method to an JavaScript Object

This JavaScript example shows how to add a method to an existing JavaScript object.

Adding a Method to an Object Example

Adding a new method to an object is easy:
var user = {
    firstName : 'Ramesh',
    lastName : 'Fadatare',
    emailId : 'ramesh@gmail.com',
    age : 29,
    getFullName : function (){
        return user.firstName + " " + user.lastName;
    }
}

user.getFirstName = function(){
    return this.firstName;
}

console.log(user.getFirstName());
Output:
Ramesh

Comments