Invoking Object Methods

Functions vs. Methods

At this point, we've mostly seen objects with properties that behave more like attributes. That is, properties such ascolorortypeare data that describe an object, but they don't "do" anything. We can extend _functionality _to objects by adding methods to them.

Say that we have a function,sayHello(), which simply logs a message to the console:

function sayHello () {
  console.log('Hi there!');
}

Now, say that we also have adeveloperobject with a single property,name:

const developer = {
  name: 'Andrew'
};

If we want to add thesayHello()function into thedeveloperobject, we can add the same way as we add other new properties: by providing property name, then giving it a value. This time, the value of the property is afunction!

developer.sayHello = function () {
  console.log('Hi there!');
};

This is how the updateddeveloperobject looks:

{
  name: 'Andrew',
  sayHello: function () {
    console.log('Hi there!');
  }
}

So now that asayHelloproperty has been defined, how do we go about calling (i.e., invoking) its referenced function?

Calling Methods

We can access a function in an object using the property name. Again, another name for a function property of an object is amethod. We can access it the same way that we do with other properties: by using dot notation or square bracket notation. Let's take a look back at the updateddeveloperobject above, then invoke itssayHello()method:

const developer = {
  name: 'Andrew',
  sayHello: function () {
    console.log('Hi there!');
  }
};
developer.sayHello();
// 'Hi there!'

developer['sayHello']();
// 'Hi there!'

Just like calling a function, an object's method is called by adding parentheses at the end of the method's name. Note that both dot notation and square bracket notation return the same result!

Passing Arguments Into Methods

If the method takes arguments, you can proceed the same way, too:

const developer = {
  name: 'Andrew',
  sayHello: function () {
    console.log('Hi there!');
  },
  favoriteLanguage: function (language) {
    console.log(`My favorite programming language is ${language}`);
  }
};


developer.favoriteLanguage('JavaScript');
// My favorite programming language is JavaScript'

Let's see this all in action!

VIDEO

Here's the code from the preceding video.

QUESTION 1 OF 6

What is true about object methods? Select all that apply:

  • Unlike how regular functions are invoked, to invoke a method you can simply access the object's property without parentheses (()).

  • Methods cannot accept any arguments.

  • Methods can be called without a receiving object.

  • A method is a property that points to a function.

SUBMIT: A method is a property of an object whose value is a function. Methods are called on objects in the following format: object.method().

Write an expression that invokes thealerter()function in the following array,myArray:

const myArray = [ function alerter() { alert('Hello!'); } ];

SUBMIT: myArray[0]();

Write an expression that invokes the function referenced by thebellobject'sringproperty:

const bell = {
  color: 'gold',
  ring: function () {
    console.log('Ring ring ring!');
  }
};

SUBMIT: bell.ring();

💡 Call Methods by Property Name 💡

We've been using _anonymous _functions (i.e., functions without a name) for object methods. However, _naming _those functions is still valid JavaScript syntax. Consider the following object,greeter:

const greeter = {
  greet: function sayHello() {
    console.log('Hello!');
  }
};

Note that thegreetproperty points to a function with a name:sayHello. Whether this function is named or not,greetis invoked the same way:

greeter.greet();


// 'Hello!'

Named functions are great for a smoother debugging experience, since those functions will have a useful name to display in stack traces. They're completely optional, however, and you'll often read code written by developers who prefer one way or the other.

A Method Can Access the Object it was Called On

Recall that an object can contain data and the means to manipulate that data. But just _how _can an object reference its own properties, much less _manipulate _some of those properties itself? This is all possible with thethiskeyword!

Usingthis, methods can directly access the object that it is called on. Consider the following object,triangle:

const triangle = {
  type: 'scalene',
  identify: function () {
    console.log(`This is a ${this.type} triangle.`);
  }
};

Note that inside theidentify()method, the valuethisis used. When you saythis, what you're really saying is "_this_object" or "the object at hand."thisis what gives theidentify()method direct access to thetriangleobject's properties:

triangle.identify();


// 'This is a scalene triangle.'

When theidentify()method is called, the value ofthisis set to the object it was called on:triangle. As a result, theidentify()method can access and usetriangle'stypeproperty, as seen in the aboveconsole.log()expression.

Note thatthisis a reserved word in JavaScript, and cannot be used as an identifier (e.g. variable names, function names, etc.).

VIDEO

Here's the code from the preceding video.

QUESTION 4 OF 6

What is true aboutthis? Select all that apply:

  • thisrefers to "this property," or "this method."

  • Usingthis, methods can access and manipulate an object's properties.

  • The exact value ofthisis set before a method is invoked.

  • thisis a reserved word in JavaScript.

SUBMIT: A value for this is set when a method is invoked on an object, and that value refers to that object . Since it is a reserved word, it should not be used as any variable name, function name, etc.

Let's make sure we're still on the same page! Write an expression that invokes the function referenced by thetreeobject'sgrowOneFootproperty:

const tree = {
  type: 'redwood',
  leaves: 'green',
  height: 80,
  age: 15,
  growOneFoot: function () {
    this.height += 1;
  }
};

SUBMIT: tree.growOneFoot();

/*
Create an object called `chameleon` with two properties:
1. `color`, whose value is initially set to 'green' or 'pink'
2. `changeColor`, a function which changes `chameleon`'s `color` to 'pink'
if it is 'green', or to 'green' if it is 'pink'
*/

const chameleon = {
    color: 'green',
    changeColor: function() {
        if (this.color === 'green') {
            this.color = 'pink';
        } else {
            this.color = 'green';
        }
    }
};

💡 The value ofthis💡

Depending on _how _a function is called,thiscan be set to different values! Later in this course, we'll take a deep dive into different ways that functions can be invoked, and how each approach influences the value ofthis.

Summary

Amethodis a function property of an object. It is accessed the same way as any other property of the object (i.e., using dot notation or square bracket notation), and is invoked the same way as a regular function outside of an object (i.e., adding parentheses to the end of the expression).

Since an object is a collection of data and the means to operate on that data, a method can access the object it was called on using the specialthiskeyword. The value ofthisis determined when a method is invoked, and its value is the object on which the method was called. Sincethisis a reserved word in JavaScript, its value cannot be used as an identifier. Feel free to check out the links below for an additional look at methods and their relationship withthis.

We've spent a bit of time onthisinside objects, but did you know that the value ofthiscan have different meanings_outside_an object? In the next section, we'll take a close look at globals, their relationship withthis, and the implications of using them.

Further Research

results matching ""

    No results matching ""