Object Methods

When a property value is actually a function, the property is considered a method.

You can add a method to an object in the same way that you would add a property.

var person = {
 name: "Nicholas",
 sayName: function() {
 console.log(person.name);
 }
};

person.sayName(); // outputs "Nicholas"\

The this Object

You may have noticed something strange in the previous example. The sayName() method references person.name directly, which creates tight coupling between the method and the object. This is problematic for a number of reasons. 

Solution: Every scope in JavaScript has a this object that represents the calling object for the function.

var person = {
 	name: "Nicholas",
 	sayName: function() {
 		console.log(this.name);
	}
};

person.sayName(); // outputs "Nicholas"


This code works the same as the earlier version, but this time, sayName() references this instead of person. That means you can easily change the name of the variable or even reuse the function on different objects.


function sayNameForAll() {
 	console.log(this.name);
}

var person1 = {
 	name: "Nicholas",
 	sayName: sayNameForAll
};

var person2 = {
 	name: "Greg",
 	sayName: sayNameForAll
};

var name = "Michael";

person1.sayName(); // outputs "Nicholas"
person2.sayName(); // outputs "Greg"
sayNameForAll(); // outputs "Michael"


When sayNameForAll() is called directly, it outputs "Michael" because the global variable is considered a property of the global object

References

 THE PRINCIPLES OF OBJECT-ORIENTED JAVASCRIPT. Copyright © 2014 by Nicholas C. Zakas