Start learning free

LESSON 180 OF 344 · OBJECT-ORIENTED PROGRAMMING

Class Methods in JavaScript: Defining Behavior

Lesson Read the full explanation

TL ; DR:

  • A method is a function that lives inside a class. Inside the method, this refers to the object it was called on.


  • Define methods inside the class body — no function keyword needed:

    class Dog {
        constructor(name) {
            this.name = name;
        }
    
        bark() {
            console.log("Woof! I am " + this.name);
        }
    }
    

  • Call it on an object with the dot operator: dog.bark();



Full lesson:

So far you've added data to a class with properties set in the constructor. The other half of OOP is behavior — actions an object can perform. That's what methods are for.


Defining a method

Inside a class body, you write methods without the function keyword:

bark() {
    console.log("Woof! I am " + this.name);
}

Use this.name to read the property of the current object.


Your task

Add a bark method that logs "Woof! I am " followed by this.name.

Woof! I am Rex
STEP 1 OF 2
    Ctrl + Enter to check

    JAVASCRIPT · OBJECT-ORIENTED PROGRAMMING

    Class Methods in JavaScript, explained

    Data and behavior

    Properties hold what an object knows. Methods describe what it can do. A method is a function that lives inside a class, and every object made from the class can call it. Inside the method, this refers to the object the method was called on, so the same code works on whichever object calls it.

    Defining a method

    Methods go in the class body. You write the name, the parameter list and the body, with no function keyword:

    class Dog {
        constructor(name) {
            this.name = name;
        }
    
        bark() {
            console.log("Woof! I am " + this.name);
        }
    }
    

    Methods in a class are not separated by commas or semicolons. A comma between them is a SyntaxError, which is a common slip for people used to object literals.

    Calling a method

    You call a method on an object with the dot operator and parentheses:

    let rex = new Dog("Rex");
    rex.bark();    // Woof! I am Rex
    
    let luna = new Dog("Luna");
    luna.bark();   // Woof! I am Luna
    

    The code of bark is written once, yet each call prints a different name. That works because, in rex.bark(), this is rex, and in luna.bark() it is luna. The object to the left of the dot becomes this.

    Parameters and return values

    Methods take parameters and return values like any function:

    class Dog {
        constructor(name) {
            this.name = name;
        }
    
        greet(person) {
            return "Hi " + person + ", I am " + this.name;
        }
    }
    
    let rex = new Dog("Rex");
    console.log(rex.greet("Ann"));   // Hi Ann, I am Rex
    

    Notice that greet returns a string and leaves the printing to the caller. A method that returns a value is easier to reuse than one that only logs.

    Methods can change state and call each other

    A method can read and also change the object's properties, and it can call the object's other methods through this:

    class Dog {
        constructor(name) {
            this.name = name;
            this.energy = 3;
        }
    
        bark() {
            console.log("Woof! I am " + this.name);
        }
    
        play() {
            this.energy = this.energy - 1;
            this.bark();
        }
    }
    
    let rex = new Dog("Rex");
    rex.play();                  // Woof! I am Rex
    console.log(rex.energy);     // 2
    

    This is the main reason to put behavior in a class: the methods and the data they work on sit together.

    The exercise, step by step

    The starter code has the constructor and a call to rex.bark(), but the class has no bark method. Calling a missing method fails with TypeError: rex.bark is not a function.

    1. Declare an empty method. Below the constructor, inside the class, write bark() { }, with no parameters. Calls such as rex.bark() now succeed, though they do nothing yet.
    2. Fill in the body. Log "Woof! I am " joined with this.name using console.log. The this. matters: it selects the property of the dog the method was called on.

    The solution in JavaScript

    class Dog {
        constructor(name) {
            this.name = name;
        }
    
        bark() {
            console.log("Woof! I am " + this.name);
        }
    }
    
    let rex = new Dog("Rex");
    rex.bark();
    

    The output is:

    Woof! I am Rex
    

    Where methods live

    A method is not copied into every object. JavaScript stores it once, on the class's prototype, and each object looks it up there when you call it. You can see this in the results: Object.keys(rex) lists only ["name"], and rex.bark === luna.bark is true, because both dogs share one function. This keeps objects small, and it is why this is needed: the shared function has to be told which object it is working on.

    Common mistakes

    • Writing name instead of this.name. A bare name is a variable lookup, not a property lookup. In Node it fails with ReferenceError: name is not defined. Properties are always reached through this.
    • Using the function keyword. Writing function bark() { ... } inside a class is a syntax error. Write bark() { ... }.
    • Forgetting the parentheses on the call. rex.bark is the function itself, and nothing runs. rex.bark() calls it.
    • Detaching the method from its object. After let f = rex.bark; f();, the call has no object to the left of the dot, so this is undefined inside the class and the line this.name throws TypeError: Cannot read properties of undefined (reading 'name'). This happens when a method is passed around as a callback. rex.bark.bind(rex) creates a version tied to rex.
    • Putting commas between methods. Commas are for object literals, not class bodies.

    Key takeaways

    • A method is a function declared in a class body, written without function and without commas between methods.
    • Call it as object.method(); inside it, this is that object.
    • Reach the object's properties through this, as in this.name.
    • Methods are shared through the prototype, so each object stores only its own data.
    Keep going with JavaScriptAbout 340 step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free