Categories
JavaScript Tutorials

Calling an Object’s Methods

Because a method is just a property that happens to be a function, you can access methods in the same way as you would access properties: using the dot notation or using square brackets. Calling (invoking) a method is the same as calling any other function: just add parentheses after the method name, which effectively say “Execute!”.

var hero = {
  breed: 'Turtle',
  occupation: 'Ninja',
  say: function() {
    return 'I am ' + hero.occupation;
  }
}
hero.say();
//"I am Ninja"

If there are any parameters that you want to pass to a method, you proceed as with normal functions:

hero.say('a', 'b', 'c');

Because you can use the array-like square brackets to access a property, this means you can also use brackets to access and invoke methods, although this is not a common practice:

Examples

Create an object with firstname and lastname property and also a method that prints the full name in console. Call the method to print the output.

var person = {
  firstname: 'Bob',
  lastname: 'Smith',
  printName: function() {
               console.log(person.firstname + ' ' + person.lastname);
             }
};
person.printName();

Create an object with a property that contains another object which contains a method. Call the method of the inner object.

var org = {
  name: 'ABC Technologies',
  details: {
    employees: 550,
    printOrgInfo: function() {
                    console.log(org.name + ' ' + 'consists of' + ' ' + org.details.employees + ' ' + 'employees');
                  }
  }
}
org.details.printOrgInfo();