Arrays and Objects in JS 9/11


#1

Can anyone explain the following code?

var phonebookEntry = {};

phonebookEntry.name = 'Oxnard Montalvo';
phonebookEntry.number = '(555) 555-5555';
phonebookEntry.phone = function() {
  console.log('Calling ' + this.name + ' at ' + this.number + '...');
};

phonebookEntry.phone();

#2

The program starts by declaring and defining a variable that is assigned an empty object.

var phonebookEntry = {};

An object is a data construct with a context in which to scope data and methods that can work with that data.

These two lines construct data:

phonebookEntry.name = 'Oxnard Montalvo';
phonebookEntry.number = '(555) 555-5555';

We have defined the name and number properties of the phonebookEntry object. If we log the object,

console.log(phonebookEntry);

we get,

{ name: 'Oxnard Montalvo', number: '(555) 555-5555' }

The phone property is defined as an anonymous function, which in context is known as a method. Being a function in the same context as the data means there is a this variable to refer to an execution context. The method can access variables of this object.

phonebookEntry.phone = function() {
    console.log('Calling ' + this.name + ' at ' + this.number + '...');
};