Adding Methods to Classes
When you define a method inside a JavaScript class, you are creating an instance method. This means every object created from that class will have access to the method, but the method itself is shared by all instances rather than being duplicated for each one. Defining methods in the class body (outside the constructor) attaches them to the class's prototype. This makes your code more efficient, since only one copy of the method exists in memory, regardless of how many objects you create from the class.
To add a method, simply write its name followed by parentheses and a code block within the class definitionβthere is no need for the function keyword. These methods can access the instance's properties using the this keyword.
123456789101112class Person { constructor(name) { this.name = name; } greet() { return "Hello, my name is " + this.name + "!"; } } const alice = new Person("Alice"); console.log(alice.greet()); // Output: Hello, my name is Alice!
Thanks for your feedback!
Ask AI
Ask AI
Ask anything or try one of the suggested questions to begin our chat
Can you explain the difference between instance methods and static methods in JavaScript classes?
How does the `this` keyword work inside class methods?
Can you show how to add more methods or properties to the `Person` class?
Awesome!
Completion rate improved to 6.25
Adding Methods to Classes
Swipe to show menu
When you define a method inside a JavaScript class, you are creating an instance method. This means every object created from that class will have access to the method, but the method itself is shared by all instances rather than being duplicated for each one. Defining methods in the class body (outside the constructor) attaches them to the class's prototype. This makes your code more efficient, since only one copy of the method exists in memory, regardless of how many objects you create from the class.
To add a method, simply write its name followed by parentheses and a code block within the class definitionβthere is no need for the function keyword. These methods can access the instance's properties using the this keyword.
123456789101112class Person { constructor(name) { this.name = name; } greet() { return "Hello, my name is " + this.name + "!"; } } const alice = new Person("Alice"); console.log(alice.greet()); // Output: Hello, my name is Alice!
Thanks for your feedback!