Summary of “Objects”. Part 2

Objects can store any types of data, including functions. Such function properties are called object methods. The method call is written like this: object.method().

From within methods, you can access properties and other methods of an object using the this keyword. When you call object.method(), this refers to the object before the dot. That object is called the call context.

Important detail: for these methods, what this refers to is determined by how the method is called.

var cat = {
  name: 'Muffin',
  color: 'red',
  age: 5,

  getGreeting: function () {
    return 'Meow, hello! My name is ' + this.name;
  }
};

console.log (cat.getGreeting());
// Logs 'Meow, hello! My name is Muffin'

Maps or dictionaries are very convenient to use. In our example, they store the relationship between the cat’s name and his favorite delicacy.

var catsFavoriteFood = {
  Muffin: 'fish',
  Rudolph: 'cutlet',
  Snowball: 'milk'
};

var printFavoriteFood = function (name) {
  // Using bracket notation
  return 'My favorite food is ' + catsFavoriteFood[name];
};

console.log(printFavoriteFood('Snowball'));
// Logs 'My favorite food is milk'

Continue