cf.completefrontendCode editorOpen lab
THE JAVASCRIPT FIELD GUIDE

Methods & this

Learn how functions stored on objects become methods, how this is chosen by the call shape, and how returning this powers method chaining.

By the end, you can
  • 01
    Write method shorthandStore functions on objects with greet() {} and read sibling properties with this.
  • 02
    Predict thisUse the object before the dot to explain obj.method() calls, including one lost-this case.
  • 03
    Build chainsReturn this from mutating methods so calls can continue in a readable line.

Methods are functions that belong to objects

In Object basics, objects held data: names, scores, settings, and other properties. A property can also hold a function. When you call a function through an object, programmers call it a method.

A function stored on an objectPop out in the code editor (opens in a new tab)JavaScript
const dog = {  name: "Pixel",  bark: function () {    return dog.name + " says woof";  },}; console.log(dog.bark()); // Pixel says woof

That works, but dog.name is glued to one variable name. If the same function is shared with another object, hard-coding dog is too stiff. JavaScript gives methods a special word, this, for “the object this method is working with right now.”

Real-life analogyA method is a skill a person has

Think of an object as a character card. It has facts, like a name, and skills, like bark or introduce. A method is one of those skills. When Pixel uses the skill, the word “my” points at Pixel.

In real life: Pixel has the skill bark
In JavaScript: dog.bark() stores a function on dog
In real life: The skill can use Pixel’s name
In JavaScript: The method reads this.name
In real life: Another dog can use the same skill
In JavaScript: The same function can be called as nori.bark()

Where the analogy stops: A real skill is physically part of a dog. In JavaScript, the function value can be copied to another object or stored in a variable, which is why the call shape matters.

This lesson keeps to the core rule you need now: for a regular method call shaped like object.method(), this is the object before the dot, chosen when the call happens. The full rule book—call, apply, bind, global values, and strict-mode details—gets its own Stage 4 module.

Method shorthand

STEP THROUGH

Most object methods use shorthand. Instead of writing bark: function () { ... }, write bark() { ... }. For everyday calls, they behave the same: both store a regular function in the bark property. One advanced difference is that shorthand methods are not meant to be used with new; constructors are the next lesson.

Old style and shorthandPop out in the code editor (opens in a new tab)JavaScript
const oldStyle = {  name: "Ada",  greet: function () {    return "Hi " + this.name;  },}; const shorthand = {  name: "Ada",  greet() {    return "Hi " + this.name;  },};

The important part is not the shorter spelling. It is the way the method reads nearby data. this.name means “the name property on the object currently using this method.”

Step through method shorthand
Step 0 of 4Ready
Your turn: follow the blue line

Predict what dog.bark() prints. Then step through how method shorthand and this work together.

Running in
  1. script
Next: line 1
Click the blue line to take the next stepPop out in the code editor (opens in a new tab)JavaScript
  name: "Pixel",  bark() {    return this.name + " says woof";  },}; console.log(dog.bark());
CallStoreChangeResultRun = next line. Ran = already executed.
Recent returnsNothing yet. Start with the blue line.
A guided replay recorded from real JavaScript calls, not an engine debugger. Step follows executed statements; Back reviews a snapshot. Reset starts a fresh run.
A method is still a value

A method is a function value stored in a property. Objects do not permanently stamp ownership onto functions. That is why the next section focuses on the call shape, not on where the function was written.

this is decided at call time

INTERACTIVE

Here is the rule to practice until it feels automatic: look at the actual call. In ada.introduce(), the object before the dot is ada, so this is ada. In lin.introduce(), the object before the dot is lin, so the same function sees a different this.

Who is this? Change the call shape
Step 0 of 6Ready
Your turn: follow the blue line

Choose a call shape, then step through the same function using a different this.

Running in
  1. script
Next: line 2
Click the blue line to take the next stepPop out in the code editor (opens in a new tab)JavaScript
"use strict";  return "Hi, I am " + this.name;} const ada = { name: "Ada", introduce };const lin = { name: "Lin", introduce }; ada.introduce();
CallStoreChangeResultRun = next line. Ran = already executed.
Recent returnsNothing yet. Start with the blue line.
Choose the last line, then predict this.name

Changing the call starts a fresh replay. The same function can receive a different this.

A guided replay recorded from real JavaScript calls, not an engine debugger. Step follows executed statements; Back reviews a snapshot. Reset starts a fresh run.

The detached version is deliberately honest. Site modules are strict code, and the displayed snippet starts with "use strict". When the last line is speak(), there is no object before the dot. In strict code, this is undefined, so reading this.name throws a TypeError.

Real-life analogythis is like “me” or “my”

The word “my” changes meaning depending on who is speaking. If Ada says “my laptop,” it is Ada’s laptop. If Lin says the same words, it is Lin’s laptop. this works like that for method calls: its meaning comes from the caller right now.

In real life: Ada says “my name”
In JavaScript: ada.introduce() makes this be ada
In real life: Lin says “my name”
In JavaScript: lin.introduce() makes this be lin
In real life: A quote with no speaker is confusing
In JavaScript: speak() has no object before the dot

Where the analogy stops: Human sentences have grammar and context. JavaScript uses a precise call rule for regular methods, and there are more call forms later.

Arrows, callbacks, and losing this

SORT

Arrow functions, from the Arrow functions lesson, have no own this. That makes them great inside a method when they should keep the method’s this, and risky as the method itself when you expected object.method() behavior.

Regular methods vs arrow functions
ShapeGets object as this?Good use
greet() { return this.name; }Yes, when called as obj.greet()Object methods that read or change sibling properties
greet: function () { return this.name; }Yes, when called as obj.greet()Older spelling of the same everyday idea
greet: () => this.nameNoRare as an object method; it keeps outer this instead
() => obj.greet()The arrow has no own this, but it performs a real method callCallback wrapper to avoid losing this
Arrow method vs arrow inside a methodPop out in the code editor (opens in a new tab)JavaScript
const user = {  name: "Mina",  regular() {    return this.name;  },  arrow: () => this.name,}; console.log(user.regular());console.log(user.arrow());
An arrow inside a method can keep thisPop out in the code editor (opens in a new tab)JavaScript
const team = {  prefix: "Team",  names: ["Ada", "Lin"],  labels() {    return this.names.map((name) => this.prefix + ": " + name);  },}; console.log(team.labels().join(", "));

Callbacks are the other common trap. Passing ada.introduce to something like setTimeout passes the function value by itself. It is no longer called as ada.introduce(). A simple fix is an arrow wrapper: () => ada.introduce(). You will also learn bind in Stage 4.

What is this?
  • dog.bark()
  • app.user.sayName()
  • const fn = dog.bark; fn()
  • setTimeout(dog.bark, 0)
  • setTimeout(() => dog.bark(), 0)
  • const dog = { bark: () => this.name }
Try it yourself
0 of 6 correct

Sort each call shape by what happens to this. Focus on the object before the final dot.

Choose a category for every card. You can change an answer at any time; Reset clears them all.

Method chaining

INTERACTIVE

Method chaining is the pattern behind code such as counter.add(2).add(3).double().read(). Each changing method does its work, then returns this. That hands the same object to the next dot.

Real-life analogyA chain is an assembly line

Each station changes the same product, then hands it to the next station. If one station forgets to hand it over, the next station has nothing to work on. That is exactly what happens when a chainable method forgets return this.

In real life: Station 1 adds a part and passes the product on
In JavaScript: add(2) changes the object and returns this
In real life: Station 2 keeps working on the same product
In JavaScript: .add(3) receives the same object
In real life: The final inspector reports the result
In JavaScript: .read() returns the final value

Where the analogy stops: An assembly line usually has many workers. A method chain may be one object repeatedly returning itself.

Step through a method chain
Step 0 of 8Ready
Your turn: follow the blue line

Step through a chain. Watch every changing method return this so the next method has an object to call.

Running in
  1. script
Next: line 1
Click the blue line to take the next stepPop out in the code editor (opens in a new tab)JavaScript
  value: 0,  add(amount) {    this.value = this.value + amount;    return this;  },  double() {    this.value = this.value * 2;    return this;  },  read() {    return this.value;  },}; counter.add(2).add(3).double().read();
CallStoreChangeResultRun = next line. Ran = already executed.
Recent returnsNothing yet. Start with the blue line.
A guided replay recorded from real JavaScript calls, not an engine debugger. Step follows executed statements; Back reviews a snapshot. Reset starts a fresh run.
Build a counter chain
Chainable counterPop out in the code editor (opens in a new tab)JavaScript
const counter = {  value: 0,  add(amount) {    this.value = this.value + amount;    return this;  },  double() {    this.value = this.value * 2;    return this;  },  read() {    return this.value;  },}; counter.add(2).add(3).double().read();
Live chain0 calls

counter

counter.value0
resultnot run yet

Reference error when a method forgets to return: TypeError: Cannot read properties of undefined (reading 'double')

Try it yourself

Build a chain one method at a time. Start with add, then try double, then intentionally break it.

The buttons append real method calls to the chain. Reset creates a fresh counter with value 0.
When not to chain

Chain when every call naturally continues the same idea. Do not hide complicated decisions in one long line. Clear multi-line code is better than a clever chain.

Where you’ll use this

Methods show up anywhere an object has both data and behavior: form validators, shopping carts, counters, date formatters, animation builders, and tiny state objects in UI code. The object keeps related values together, and the methods describe the actions that make sense for those values.

A small text builderPop out in the code editor (opens in a new tab)JavaScript
const headline = {  text: "",  word(value) {    this.text = this.text + value + " ";    return this;  },  shout() {    this.text = this.text.toUpperCase();    return this;  },  read() {    return this.text.trim();  },}; console.log(headline.word("methods").word("click").shout().read());

The builder reads like a sentence: add a word, add another word, shout, read. The reason it works is still the same small rule: each mutating method uses this for the current object and returns this for the next call.

Common misconceptions

“A method permanently knows its object.”

No. A function value can be copied. this is chosen by the call shape, not by where the function was first stored.

“this means the object where the function was written.”

The same function can be assigned to two objects. ada.introduce() and lin.introduce() use different receivers.

“Arrow functions are shorter methods.”

They are shorter functions, but they do not have their own this. Use regular method syntax when the method reads or changes object properties.

“Callbacks keep their original object.”

Passing user.say by itself loses the method call. Wrap it as () => user.say() or learn bind later.

“Every method should return this.”

Only methods meant to keep the chain going should return this. A method such as read() should return the useful value.

Tease for next lesson

Constructors use this too, but in a different call shape: new Something(). That is why Constructors & new comes next.

Practice: methods and this

5 EXERCISES
Exercise 1 · Warm-upAdd a method that reads this

Add a describe method to the object so it prints the exact sentence in the answer checker.

Starter codePop out in the code editor (opens in a new tab)JavaScript
const book = {
  title: "Eloquent JavaScript",
  describe() {
    return this.title + " is on the shelf";
  },
};
console.log(book.describe());

Answer, then press Check. Spacing and letter case don’t matter.

    Exercise 2 · PracticePredict two callers

    Predict both printed lines before you run the code.

    Starter codePop out in the code editor (opens in a new tab)JavaScript
    "use strict";
    function label() {
      return this.name;
    }
    const first = { name: "first", label };
    const second = { name: "second", label };
    console.log(first.label());
    console.log(second.label());

    Answer, then press Check. Spacing and letter case don’t matter.

      Exercise 3 · PracticeFix a lost-this callback

      Imagine a scheduler will call callback() later. Make the callback print break time.

      Starter codePop out in the code editor (opens in a new tab)JavaScript
      const timer = {
        label: "break time",
        announce() {
          console.log(this.label);
        },
      };
      const callback = () => timer.announce();
      callback();

      Answer, then press Check. Spacing and letter case don’t matter.

        Exercise 4 · PracticeMake methods chainable

        Build a tiny object whose word method can be called twice in one chain.

        Starter codePop out in the code editor (opens in a new tab)JavaScript
        const list = {
          text: "",
          word(value) {
            this.text = this.text + value;
            return this;
          },
          read() {
            return this.text;
          },
        };
        console.log(list.word("go").word("!").read());

        Answer, then press Check. Spacing and letter case don’t matter.

          Exercise 5 · ChallengeFix an arrow method

          Rewrite the greeting as a regular method so this.name points at the object.

          Starter codePop out in the code editor (opens in a new tab)JavaScript
          const user = {
            name: "Rae",
            greet() {
              return "Hi " + this.name;
            },
          };
          console.log(user.greet());

          Answer, then press Check. Spacing and letter case don’t matter.

            Quiz: check your understanding

            7 QUESTIONS

            Every choice explains itself. For code questions, use the dot rule before you answer.

            Lesson quiz · 7 questionsScore: first tries count
            1. Question 1 of 7Which object is this inside cat.meow()?

              Choose an answer to see the explanation.

            2. Question 2 of 7What does this pet method print?

              Read the code, then predictPop out in the code editor (opens in a new tab)JavaScript
              const pet = {
                name: "Nori",
                speak() {
                  console.log(this.name);
                },
              };
              pet.speak();

              Choose an answer to see the explanation.

            3. Question 3 of 7Which syntax is method shorthand?

              Choose an answer to see the explanation.

            4. Question 4 of 7What happens in strict code when you detach a method and call it as a plain function?

              Read the code, then predictPop out in the code editor (opens in a new tab)JavaScript
              "use strict";
              const user = {
                name: "Ari",
                say() {
                  console.log(this.name);
                },
              };
              const fn = user.say;
              fn();

              Choose an answer to see the explanation.

            5. Question 5 of 7Why does counter.add(2).double() work in a chainable API?

              Choose an answer to see the explanation.

            6. Question 6 of 7What does this counter chain print?

              Read the code, then predictPop out in the code editor (opens in a new tab)JavaScript
              const counter = {
                value: 1,
                add() {
                  this.value = this.value + 1;
                  return this;
                },
                read() {
                  console.log(this.value);
                },
              };
              counter.add().add().read();

              Choose an answer to see the explanation.

            7. Question 7 of 7Which callback keeps the method call shape?

              Choose an answer to see the explanation.

            Key takeaways

            • A method is a function stored in an object property.
            • Method shorthand greet() { ... } is the common way to write regular object methods.
            • For obj.method(), this is obj, decided at call time.
            • Detached calls and bare callbacks lose the object before the dot; arrow wrappers or bind can fix that.
            • Chainable methods return this; final reader methods return the useful value.

            Remember the one-liner.
            A method is an object’s function; this is the object before the dot for that call.

            Up next: Constructors & new.

            CompleteFrontend Clear concepts. Working examples.