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.
- Declare an empty method. Below the constructor, inside the class, write
bark() { }, with no parameters. Calls such asrex.bark()now succeed, though they do nothing yet. - Fill in the body. Log
"Woof! I am "joined withthis.nameusingconsole.log. Thethis.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
nameinstead ofthis.name. A barenameis a variable lookup, not a property lookup. In Node it fails withReferenceError: name is not defined. Properties are always reached throughthis. - Using the
functionkeyword. Writingfunction bark() { ... }inside a class is a syntax error. Writebark() { ... }. - Forgetting the parentheses on the call.
rex.barkis 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, sothisisundefinedinside the class and the linethis.namethrowsTypeError: 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 torex. - 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
functionand without commas between methods. - Call it as
object.method(); inside it,thisis that object. - Reach the object's properties through
this, as inthis.name. - Methods are shared through the prototype, so each object stores only its own data.