Skip to main content

Welcome to a Grasp lesson

Create a free account to keep studying and create your own study path.

Lesson 44

Defining Object Methods

This lesson is built with resources from youtube.com, javascript.info and 1 more site.

Hello! Welcome back.

In our last lesson, you learned how to access, modify, and add data to objects using dot and bracket notation. We established that objects are great for holding related data. But what about related actions?

Today, we'll bring our objects to life. This lesson focuses on the learning outcome: Define methods (functions as properties) on objects to represent behavior. You'll discover how to attach functions to your objects, turning them from static data containers into dynamic entities that can perform tasks. We'll also introduce the essential this keyword, which allows these actions to interact with the object's own data.

From Data to Behavior: What is a Method?

So far, we've treated objects like filing cabinets for information. A user object might have name and age properties. But in the real world, a user does things: they can log in, post a comment, or change their profile picture. In JavaScript, we represent these actions by putting functions inside our objects.

A function that is a property of an object is called a method.

Imagine you're building a small application and need to manage data for several employees. You could store their pay rate and hours in separate variables, but it gets messy quickly. Objects help us group the data, and methods help us group the behavior that acts on that data.

This short video provides an excellent visual explanation of why bundling data and actions together is so powerful.

JavaScript objects explained the visual way

Watch this clip from 'JavaScript objects explained the visual way' by 3dCodeWorld. It illustrates how objects and methods help organize code and avoid the chaos of managing many separate variables and functions.

Watch from the beginning until 02:10. Pay attention to the visual metaphor of how an object 'lumps together' related properties and the functions that operate on them.


Defining Methods in an Object

Now that you understand why we use methods, let's see how to create them. There are two common syntaxes.

This image provides a great overview of an object's structure, including properties and a method. Notice the greet property holds a function.

JavaScript Object Structure with Method Definition
This diagram shows a 'person' object with properties like 'name' and a 'greet' method, which is a function assigned to a property.

The resource below will walk you through the two main ways to define a method.

Object methods, "this"

The article 'Object methods, "this"' on javascript.info provides a clear introduction to method syntax. We'll focus on the first two parts.

Please read the sections 'Method examples' and 'Method shorthand'. These sections will show you the traditional way of defining a method and the modern, cleaner syntax.

As you've just read, here are the two syntaxes:

  1. Function Expression (Classic way):

    let user = {
      name: 'Alice',
      // The 'sayHi' property holds a function
      sayHi: function() {
        console.log('Hello!');
      }
    };
    
  2. Method Shorthand (Modern ES6+ way):
    This is cleaner and generally preferred. You just omit the colon and the function keyword.

    let user = {
      name: 'Alice',
      // Shorthand syntax for a method
      sayHi() {
        console.log('Hello!');
      }
    };
    

In both cases, you call the method using dot notation followed by parentheses:
user.sayHi(); // Outputs: Hello!

The parentheses () are crucial—they are what execute the function. Without them, user.sayHi would just refer to the function itself, without running it.


Making Methods Useful with the this Keyword

A method that just prints "Hello!" isn't very dynamic. The real power of methods comes when they can access and manipulate the other properties of their own object. For instance, we want user.sayHi() to say "Hello, Alice!", using the name property from the user object.

To do this, a method needs a way to refer to the object it belongs to. This is accomplished with a special keyword: this.

Inside a method, this refers to the object the method was called on. Think of it as the method saying "the object I'm currently part of."

This next video gives a very clear, concise demonstration.

Javascript Objects Explained | Javascript Objects Tutorial

In this clip from 'Javascript Objects Explained' by Dave Gray, you'll see a practical example of using 'this' to access an object's properties from within a method.

Watch from 05:44 to 06:51. Notice how this.beverage.morning is used inside the action method to get data from the same object.

Let's solidify this with a code example.

let user = {
  name: "Bob",
  age: 42,
  
  // This method uses 'this' to access the object's properties.
  introduce() {
    console.log(`Hi, my name is ${this.name} and I am ${this.age} years old.`);
  }
};

user.introduce(); // Outputs: Hi, my name is Bob and I am 42 years old.

When user.introduce() is executed, this inside the introduce method becomes a reference to the user object. Therefore, this.name is the same as user.name.

Using this is more robust than referring to the object by its variable name (user.name). If you were to copy the object to a new variable, this would always refer to the correct object that is calling the method, while the hardcoded variable name could lead to bugs. We will explore this "dynamic" nature of this in much more detail in our next lesson.

Test your understanding!

Consider the car object below. What will be logged to the console when car.displayInfo() is called?

let car = {
  make: 'Honda',
  model: 'Civic',
  year: 2022,
  isRunning: false,
  
  startEngine() {
    this.isRunning = true;
    console.log('Engine started.');
  },

  displayInfo() {
    console.log(`This is a ${this.year} ${this.make} ${this.model}.`);
  }
};

car.displayInfo();
Show answer

The console will log: "This is a 2022 Honda Civic."

The displayInfo method uses this to access the year, make, and model properties of the car object it belongs to.


Practice: Build a Calculator Object

It's time to put these concepts into practice. Your task is to create a simple calculator object. This exercise will require you to define methods that not only read data using this but also write data back to the object.

Challenge: Create an object named calculator with three methods:

  1. read(): Asks for two values using the prompt() function and saves them as object properties a and b.
  2. sum(): Returns the sum of the saved values.
  3. mul(): Returns the product of the saved values.

Here is how it should be used:

let calculator = {
  // ... your code here ...
};

calculator.read();
alert(calculator.sum());
alert(calculator.mul());

Take a moment to try and implement this in your code editor or browser console before looking at the solution.

Show Solution and Explanation
let calculator = {
  // The sum method uses 'this' to access properties a and b.
  sum() {
    return this.a + this.b;
  },

  // The mul method also uses 'this' to access the same properties.
  mul() {
    return this.a * this.b;
  },

  // The read method uses 'this' to CREATE new properties on the object.
  read() {
    // The '+' before prompt converts the input string to a number.
    this.a = +prompt('Enter the first value:', 0);
    this.b = +prompt('Enter the second value:', 0);
  }
};

calculator.read();
alert( 'Sum = ' + calculator.sum() );
alert( 'Product = ' + calculator.mul() );

Explanation:

  • The read() method is called first. It displays two prompts to the user. The entered values are stored in new properties a and b on the calculator object itself (this.a = ...).
  • When calculator.sum() is called, this refers to the calculator object. The method can therefore access this.a and this.b (the values you just entered) and return their sum.
  • The same logic applies to calculator.mul(), which accesses the same properties and returns their product. This demonstrates how methods can both set and get data from their parent object.

Conclusion

Great job! You've taken a major step in understanding how to build more capable and organized programs in JavaScript. By giving objects methods, you give them behavior, which is a cornerstone of object-oriented programming and essential for building applications in frameworks like Next.js.

Key Takeaways:

  • A method is a function stored as a property on an object.
  • Methods allow an object to perform actions or have behavior.
  • The modern shorthand syntax (myMethod() { ... }) is the preferred way to define methods.
  • The this keyword inside a method refers to the object the method belongs to, allowing the method to access the object's data and other methods.

Next Up

In this lesson, we saw this in its most common and straightforward use case: inside a method called directly on an object. However, the value of this is one of the most powerful and sometimes tricky concepts in JavaScript because it's dynamic. In our next lesson, we will dive deeper and explore the learning outcome: Explain the purpose of the 'this' keyword and how its value is determined in a method call. We will look at different scenarios that can change the value of this and how to manage it effectively.