Calling an Object's Methods

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.

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

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

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

As you can use the array-like square brackets to access a property, you can also use brackets to access and invoke methods. But this is not used as common practice.


Best Practice Tip: No quotes
  1. Use the dot notation to access methods and properties
  2. Don't quote properties in your object literals
Altering Properties/Methods

In JavaScript you can alter properties and methods of existing objects at any time. This includes adding new properties or deleting them. You can start with a blank object and add properties later.

An empty object:

var hero = {};
Accessing a non-existing property

When you access a non-existing property of an object you will get "undefined".

typeof hero.breed

Adding some properties and a method
hero.breed = 'turtle'; = 'Leonardo';
hero.sayName = function() {return;};
Calling the method
Deleting a property

Using delete, you can delete a property in a object.



Calling the method again will no longer work.


reference to undefined property
Related Tutorial
Follow Us #
Contents +