JavaScript / JavaScript Object-Oriented Programming (OOP)

Introduction to JavaScript OOP

This tutorial provides a comprehensive introduction to Object-Oriented Programming in JavaScript. It starts with basic concepts and gradually introduces more complex principles.

Tutorial 1 of 5 5 resources in this section

Section overview

5 resources

Introduces OOP principles in JavaScript, including classes, objects, and inheritance.

Introduction

This tutorial aims to provide a comprehensive introduction to Object-Oriented Programming (OOP) in JavaScript. We'll start with basic OOP concepts and gradually delve into more complex principles, equipping you with the knowledge to write cleaner, more efficient and organized code.

By the end of this tutorial, you will be able to:
- Understand the concept of OOP and its principles
- Define and create objects in JavaScript
- Understand and use different OOP features in JavaScript like constructors, prototypes, and inheritance

Prerequisites:
- Basic understanding of JavaScript (variables, functions, loops)
- Familiarity with HTML and CSS would be beneficial but not necessary

Step-by-Step Guide

  1. Object-Oriented Programming (OOP): OOP is a programming paradigm based on the concept of "objects", which contain data and code: data in the form of properties (often known as attributes), and code, in the form of methods (functions associated with an object).

  2. Objects in JavaScript: In JavaScript, an object can be created using the object literal as follows:

    javascript var student = { name: 'John', age: 20, greet: function() { console.log('Hello, ' + this.name); } };

    Here, student is an object with properties name, age and a method greet(). this.name refers to the name property of the student object.

  3. Constructors: In JavaScript, constructors are used to create multiple objects with the same properties and methods. It's a blueprint for creating objects.

    ```javascript
    function Student(name, age) {
    this.name = name;
    this.age = age;
    this.greet = function() {
    console.log('Hello, ' + this.name);
    };
    }

    var student1 = new Student('John', 20);
    var student2 = new Student('Jane', 22);
    ```

    Here, Student is a constructor function. student1 and student2 are instances of Student.

  4. Prototypes: JavaScript uses prototypes for inheritance. Each object has a prototype object, which acts as a template object that it inherits methods and properties from.

    ```javascript
    Student.prototype.sayGoodbye = function() {
    console.log('Goodbye, ' + this.name);
    };

    student1.sayGoodbye(); // Outputs: Goodbye, John
    ```

    Here, we're adding a sayGoodbye method to the prototype of Student, making it available to all instances of Student.

Code Examples

  1. Creating an object:

    ```javascript
    var car = {
    make: 'Toyota',
    model: 'Corolla',
    year: 2010,
    start: function() {
    console.log(this.make + ' ' + this.model + ' has started.');
    }
    };

    car.start(); // Outputs: Toyota Corolla has started.
    ```

  2. Creating multiple objects using a constructor:

    ```javascript
    function Car(make, model, year) {
    this.make = make;
    this.model = model;
    this.year = year;
    this.start = function() {
    console.log(this.make + ' ' + this.model + ' has started.');
    };
    }

    var car1 = new Car('Toyota', 'Corolla', 2010);
    var car2 = new Car('Honda', 'Accord', 2015);

    car1.start(); // Outputs: Toyota Corolla has started.
    car2.start(); // Outputs: Honda Accord has started.
    ```

  3. Inheritance using prototypes:

    ```javascript
    Car.prototype.stop = function() {
    console.log(this.make + ' ' + this.model + ' has stopped.');
    };

    car1.stop(); // Outputs: Toyota Corolla has stopped.
    car2.stop(); // Outputs: Honda Accord has stopped.
    ```

Summary

In this tutorial, we have covered the basics of OOP in JavaScript, including creating objects, constructors, and inheritance with prototypes. This should provide a good foundation for further exploration of OOP in JavaScript.

For continued learning, consider studying advanced OOP concepts such as encapsulation, polymorphism, and classes in ES6.

Practice Exercises

  1. Exercise 1: Create a Person object with properties firstName, lastName, and a method getFullName().

  2. Exercise 2: Create a Book constructor with properties title, author, year and a method getSummary(). Create two Book objects.

  3. Exercise 3: Add a getAge() method to the prototype of Book that returns how many years ago the book was published.

Solutions:

  1. Solution to Exercise 1:

    ```javascript
    var person = {
    firstName: 'John',
    lastName: 'Doe',
    getFullName: function() {
    return this.firstName + ' ' + this.lastName;
    }
    };

    console.log(person.getFullName()); // Outputs: John Doe
    ```

  2. Solution to Exercise 2:

    ```javascript
    function Book(title, author, year) {
    this.title = title;
    this.author = author;
    this.year = year;
    this.getSummary = function() {
    return this.title + ' by ' + this.author;
    };
    }

    var book1 = new Book('Book Title 1', 'Author 1', '2001');
    var book2 = new Book('Book Title 2', 'Author 2', '2010');

    console.log(book1.getSummary()); // Outputs: Book Title 1 by Author 1
    console.log(book2.getSummary()); // Outputs: Book Title 2 by Author 2
    ```

  3. Solution to Exercise 3:

    ```javascript
    Book.prototype.getAge = function() {
    var currentYear = new Date().getFullYear();
    return currentYear - this.year;
    };

    console.log(book1.getAge()); // Outputs the number of years since the book was published
    console.log(book2.getAge()); // Outputs the number of years since the book was published
    ```

Keep practicing and experimenting to become more proficient with OOP in JavaScript.

Need Help Implementing This?

We build custom systems, plugins, and scalable infrastructure.

Discuss Your Project

Related topics

Keep learning with adjacent tracks.

View category

HTML

Learn the fundamental building blocks of the web using HTML.

Explore

CSS

Master CSS to style and format web pages effectively.

Explore

Python

Explore Python for web development, data analysis, and automation.

Explore

SQL

Learn SQL to manage and query relational databases.

Explore

PHP

Master PHP to build dynamic and secure web applications.

Explore

Popular tools

Helpful utilities for quick tasks.

Browse tools

Hex to Decimal Converter

Convert between hexadecimal and decimal values.

Use tool

Fake User Profile Generator

Generate fake user profiles with names, emails, and more.

Use tool

Random Password Generator

Create secure, complex passwords with custom length and character options.

Use tool

JavaScript Minifier & Beautifier

Minify or beautify JavaScript code.

Use tool

Random Number Generator

Generate random numbers between specified ranges.

Use tool

Latest articles

Fresh insights from the CodiWiki team.

Visit blog

AI in Drug Discovery: Accelerating Medical Breakthroughs

In the rapidly evolving landscape of healthcare and pharmaceuticals, Artificial Intelligence (AI) in drug dis…

Read article

AI in Retail: Personalized Shopping and Inventory Management

In the rapidly evolving retail landscape, the integration of Artificial Intelligence (AI) is revolutionizing …

Read article

AI in Public Safety: Predictive Policing and Crime Prevention

In the realm of public safety, the integration of Artificial Intelligence (AI) stands as a beacon of innovati…

Read article

AI in Mental Health: Assisting with Therapy and Diagnostics

In the realm of mental health, the integration of Artificial Intelligence (AI) stands as a beacon of hope and…

Read article

AI in Legal Compliance: Ensuring Regulatory Adherence

In an era where technology continually reshapes the boundaries of industries, Artificial Intelligence (AI) in…

Read article

Need help implementing this?

Get senior engineering support to ship it cleanly and on time.

Get Implementation Help