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; } }
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']();
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 = {};
When you access a non-existing property of an object you will get "undefined".
typeof hero.breed "undefined"
hero.breed = 'turtle'; hero.name = 'Leonardo'; hero.sayName = function() {return hero.name;};
hero.sayName(); "Leonardo"
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