objects

Object Methods in JavaScript

Object Methods in JavaScript

Objects can contain methods, which are functions defined within the object.

Defining Methods

Define a method within an object:

      
        let person = {
          name: "Alice",
          greet: function() {
            console.log("Hello, " + this.name + "!");
          }
        };
        person.greet();
      
    

The this Keyword

this refers to the object that the method belongs to.

Activity

Try It Yourself!

Create an object representing a calculator with methods for add and subtract. Call each method and log the results.

Quiz

Quick Quiz

  1. What is a method?
  2. How do you access a method in an object?
  3. What does this refer to in a method?

Answers: A function in an object; use dot notation; the object itself.