JavaScript course Lesson 3 of 6

JavaScript from zero: a class holds the method

A class puts the fields and the method on one object. new Item makes a latte. label prints latte $4.50.

Zoe is one of GoByte's characters. This post was drafted by AI agents in Zoe's voice, then fact checked, run and edited by the GoByte team.

Back to top

A class is a recipe for an object. The constructor stores the fields. Methods sit next to them, and this is the object you called the method on. new is how you make one drink.

new binds this, then the method reads it#

new Item creates an object, sets its prototype so it can find label, and calls the constructor with this bound to that object. The constructor stores name and cents on this. latte.label() looks up label and calls it with this equal to latte, which is why the method sees the right fields. The string it returns is a new string. The object keeps the original cents.

label reads the object new built
  1. namestringlatte
  2. centsnumber450
  3. label()stringlatte $4.50
class Item {
  constructor(name, cents) {
    this.name = name;
    this.cents = cents;
  }

  label() {
    const frac = String(this.cents % 100).padStart(2, "0");
    return this.name + " $" + Math.floor(this.cents / 100) + "." + frac;
  }
}

const latte = new Item("latte", 450);
console.log(latte.label());
latte $4.50

new runs the constructor#

new Item("latte", 450) creates the object and calls constructor with those arguments. this.name = name stores the argument on the object. latte.label() looks up label and calls it with latte as this. The return value is the string "latte $4.50".

Skip new and the call throws, because a class constructor cannot be called as a plain function. The error is your reminder. Objects from a class are made with new. A plain object from lesson 2 has no constructor and no label until you add one.

Each drink has its own fields#

const tea = new Item("tea", 250) has a different name and cents. latte.label() still prints latte $4.50. The method is shared. The fields are not. The next lesson shows that const does not stop a field from changing, and how to copy the object first.

Report a mistake

Your product here? Partner with us

Back to top

Discussion

No comments yet. Signed in GoByte members with a verified e-mail can join. Community guidelines

Reading is open to everyone. Commenting and voting need a GoByte account with a verified e-mail.