Properties and Methods
Part of the Object Oriented Programming section of Coddy's JavaScript journey. Lesson 13 of 56.
Classes in JavaScript allow us to define properties and methods that will be shared by all instances of the class.
Create a class with properties:
class Car {
constructor(make, model) {
this.make = make;
this.model = model;
}
}When creating an instance, the constructor sets these properties:
const myCar = new Car('Toyota', 'Corolla');
console.log(myCar.make); // Output: 'Toyota'
console.log(myCar.model); // Output: 'Corolla'Add a method to the class:
class Car {
constructor(make, model) {
this.make = make;
this.model = model;
}
getDescription() {
return `This car is a ${this.make} ${this.model}.`;
}
}Now we can call this method on any instance:
const myCar = new Car('Toyota', 'Corolla');
console.log(myCar.getDescription()); // Output: 'This car is a Toyota Corolla.'Challenge
Create a class named Book in the book.js file with the following:
- A constructor that takes
title,author, andpagesparameters and sets them as properties. - A method called
getInfothat returns a string in the format: “Title: [title], Author: [author], Pages: [pages]” - Export the class by adding `export` in front of the `class` declaration
Try it yourself
import { Book } from './book.js';
// Test (do not modify this part)
const book = new Book("JavaScript Basics", "John Doe", 200);
console.log(book.getInfo());
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 InheritanceOverriding & Area MethodStatic Shape Counter9Static Methods & Properties
Class-Level vs. Instance-LevelStatic PropertiesStatic Utility MethodsRecap challengePractice on your own: Online JavaScript compiler