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.

snippet
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 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.

hero['say']();

Note
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

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

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

delete hero.name;

true

Calling the method again will no longer work.

hero.sayName();

reference to undefined property hero.name
Related Tutorial
Follow Us
https://www.facebook.com/Rookie-Nerd-638990322793530 https://twitter.com/RookieNerdTutor https://plus.google.com/b/117136517396468545840 #
Contents