BeginnerCoder
intermediate#javascript#oop

Introduction to JavaScript Object-Oriented Programming

This article was AI-drafted and has not been reviewed yet. Spotted a mistake? Tell us.

Learn how to use object-oriented programming in JavaScript to create reusable code.

Introduction to JavaScript Object-Oriented Programming

Object-oriented programming (OOP) is a programming paradigm that uses objects to represent data and behavior. In this tutorial, we will cover the basics of JavaScript OOP.

Creating an Object

To create an object in JavaScript, you can use the {} syntax or the Object constructor. Here is an example of how to create an object:

let person = { name: 'John Doe', age: 30 };

Constructors and Prototypes

Constructors are used to create new objects, and prototypes are used to define the behavior of objects. Here is an example of how to use a constructor and prototype:

function Person(name, age) {
  this.name = name;
  this.age = age;
}
Person.prototype.greet = function() {
  console.log(`Hello, my name is ${this.name} and I am ${this.age} years old.`);
}
let person = new Person('John Doe', 30);
person.greet();

Inheritance

Inheritance is used to create a new object that inherits the behavior of an existing object. Here is an example of how to use inheritance:

function Animal(name) {
  this.name = name;
}
Animal.prototype.eat = function() {
  console.log(`${this.name} is eating.`);
}
function Dog(name) {
  Animal.call(this, name);
}
Dog.prototype = Object.create(Animal.prototype);
Dog.prototype.bark = function() {
  console.log(`${this.name} is barking.`);
}
let dog = new Dog('Rex');
dog.eat();
dog.bark();

Conclusion

In this tutorial, we covered the basics of JavaScript OOP. We learned how to create objects, use constructors and prototypes, and implement inheritance.

Keep going with javascript

Ready for more? Optional paid resources that pick up where this lesson leaves off.

Some links on this page are affiliate links: we may earn a commission at no extra cost to you. As an Amazon Associate I earn from qualifying purchases.