JavaScript
This page gently explains JavaScript class syntax as a blueprint for objects that share data and behavior.
What you will learn
- How to use a
classas a blueprint - What
constructor,this, andnewdo - How to create instances that share data and behavior
class
A class is a template for creating objects with common properties and methods. For example, a Dog class can describe what every dog object stores and does, while each object can have its own name.
A basic class
JavaScript
class Dog {
constructor(name) {
this.name = name;
}
bark() {
console.log(this.name + " says woof!");
}
}
const pochi = new Dog("Pochi");
pochi.bark(); // Pochi says woof!class Dog { ... }defines the blueprint.constructor(name)runs when a new object is created and sets its initial data.this.namestores the name on the current object.bark()is a method shared by objects made from the class.new Dog("Pochi")creates an actual object, called an instance.
When is a class useful?
Classes are useful when many objects have the same kinds of data and actions. Do not create a class only because it is available; a small object or a function may be clearer when there is no shared structure.