Creating Instances
Part of the Object Oriented Programming section of Coddy's JavaScript journey — lesson 12 of 56.
After defining a class, you can create objects based on that class using the new keyword. These objects are called instances.
Let's say we have a simple Person class:
class Person {
constructor(name, age) {
this.name = name;
this.age = age;
}
greet() {
return `Hello, my name is ${this.name}`;
}
}Create an instance of the Person class:
const john = new Person("John", 30);After executing the above code, john is an instance of the Person class with:
nameproperty set to "John"ageproperty set to 30
You can access properties and methods of the instance:
console.log(john.name); // Outputs: John
console.log(john.greet()); // Outputs: Hello, my name is JohnYou can create multiple instances from the same class:
const sarah = new Person("Sarah", 25);
console.log(sarah.name); // Outputs: SarahChallenge
You're given a Student class. Your task is to create two student instances in the driver.js file:
- Create
student1with name "Sarah" and grade 85 - Create
student2with name "Mike" and grade 92
Cheat sheet
To create an instance of a class, use the new keyword:
const john = new Person("John", 30);Access properties and methods of an instance using dot notation:
console.log(john.name); // Outputs: John
console.log(john.greet()); // Outputs: Hello, my name is JohnYou can create multiple instances from the same class:
const sarah = new Person("Sarah", 25);
console.log(sarah.name); // Outputs: SarahTry it yourself
import { Student } from './student.js';
// TODO: Create an instance of class Student called student1 with name "Sarah" and grade 85
// TODO: Create an instance of class Student called student2 with name "Mike" and grade 92
// Test code - don't modify
console.log(student1.name); // Should output "Sarah"
console.log(student2.grade); // Should output 92This 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