What is a Class?
Part of the Object Oriented Programming section of Coddy's JavaScript journey — lesson 11 of 56.
A class in JavaScript is a blueprint for creating objects with pre-defined properties and methods. Classes were introduced in ES6 and provide a cleaner, more intuitive syntax for creating objects and dealing with inheritance.
Define a simple class:
class Person {
constructor(name, age) {
this.name = name;
this.age = age;
}
}The constructor method is a special method that gets called when an object is created from the class.
Create an instance of the class:
const john = new Person("John", 25);Access properties of the created object:
console.log(john.name); // Output: "John"
console.log(john.age); // Output: 25Challenge
Create a class named Car with a constructor that takes two parameters: make and model. The constructor should set these values as properties of the object.
Cheat sheet
A class is a blueprint for creating objects with pre-defined properties and methods.
Define a class with a constructor:
class Person {
constructor(name, age) {
this.name = name;
this.age = age;
}
}The constructor method is called when an object is created from the class.
Create an instance of the class:
const john = new Person("John", 25);Access properties of the object:
console.log(john.name); // Output: "John"
console.log(john.age); // Output: 25Try it yourself
// TODO: Create a class named Car
// TODO: Add a constructor that takes two parameters: make and model
// TODO: Set these values (make and model) as properties of the object
// Don't modify the code below
const make = inp[0];
const model = inp[1];
const car = new Car(make, model);
console.log(car.make)
console.log(car.model)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