Adding Methods to Objects
Part of the Object Oriented Programming section of Coddy's JavaScript journey — lesson 2 of 56.
Objects in JavaScript can contain not only data properties but also methods - functions that belong to the object.
Create a simple object with a property:
const person = {
name: "John"
};Add a method to the object:
const person = {
name: "John",
greet: function() {
return "Hello!";
}
};Call the method:
person.greet(); // Returns "Hello!"You can also use the shorthand syntax introduced in ES6:
const person = {
name: "John",
greet() {
return "Hello!";
}
};Challenge
Add an add method to the calculator object that takes two numbers and returns their sum.
Example usage:
calculator.add(5, 3); <i>// returns 8</i>
Cheat sheet
Objects in JavaScript can contain methods - functions that belong to the object.
Add a method to an object:
const person = {
name: "John",
greet: function() {
return "Hello!";
}
};Call the method:
person.greet(); // Returns "Hello!"ES6 shorthand syntax for methods:
const person = {
name: "John",
greet() {
return "Hello!";
}
};Try it yourself
let a = parseInt(inp[0]); // Don't change this line
let b = parseInt(inp[1]); // Don't change this line
// The calculator object already exists
const calculator = {
// TODO: Add the 'add' method here that takes two numbers and returns their sum
};
console.log(calculator.add(a, b));This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Object Oriented Programming
1Objects & The this Keyword
Quick Review: ObjectsAdding Methods to ObjectsUnderstanding the this KeywordConstructor FunctionsThe new KeywordRecap Challenge7 Inheritance & The extends Key
InheritanceThe "is-a" RelationshipThe extends KeywordThe super() MethodInheriting Properties&MethodsRecap Challenge2Organizing Code
What are Modules?Exporting with exportImporting with importDefault vs. Named Exports8Organizing OOP Code
Organize Classes into Modules11Project: A Shape Renderer
Setup: Shape Class & ExportCircle Class Inheritance9Static Methods & Properties
Class-Level vs. Instance-LevelStatic PropertiesStatic Utility MethodsRecap challenge