Ad space (banner)
🟨JavaScript Lessons
Lesson 10 / 69

Using Classes (Object-Oriented Programming)

In this lesson you'll learn the basics of object-oriented programming using JavaScript's class syntax, so you can handle data that shares common characteristics together. This is for people searching "JavaScript class usage" or "JavaScript what is a constructor."

A class is a "blueprint" for objects that share similar characteristics. You define a class with class, and use new to create an actual object (an instance) from that blueprint. Imagine an "animal blueprint" that lets you create as many concrete instances as you like — "dog," "cat," and so on. The constructor is a special method called first whenever an instance is created, used to set up its initial state.

The sample code gives the Animal class two properties, name and sound, and builds a sound message using a method called speak(). Writing new Animal("Dog", "Woof") creates a single instance (dog) holding that information, and dog.speak() calls the processing that's specific to that instance.

A common beginner stumbling block is understanding what this refers to. Inside a class, this refers to "the very instance currently being created," but that's easy to find confusing until you get used to it. Also remember that trying to call a class without new results in an error.

In real development, designing data that represents a "thing" — a user, a product, an order — as a class is the basic idea behind object orientation. The larger the application, the more the quality of this kind of class design affects the maintainability of the entire codebase, which is why it's taken seriously in real projects.

A class can have any number of methods added to it — not just "make a sound," but also behaviors like "eat" and "walk" can all be defined together. Bundling related data (properties) and processing (methods) into a single class makes your code easier to follow and easier to reuse.

Classes also have a mechanism called "private fields" for properties you don't want changed directly from outside the class. Prefixing a property name with # makes it inaccessible from outside the class, enabling safer class design.

JavaScript
OUTPUT

💡 Anything passed to console.log() appears in the output below.

Ad space (banner)
Ad space (in-article)