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.
Section overview
5 resourcesIntroduces 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
-
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).
-
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,
studentis an object with propertiesname,ageand a methodgreet().this.namerefers to thenameproperty of thestudentobject. -
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,
Studentis a constructor function.student1andstudent2are instances ofStudent. -
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
sayGoodbyemethod to the prototype ofStudent, making it available to all instances ofStudent.
Code Examples
-
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.
``` -
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.
``` -
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
-
Exercise 1: Create a
Personobject with propertiesfirstName,lastName, and a methodgetFullName(). -
Exercise 2: Create a
Bookconstructor with propertiestitle,author,yearand a methodgetSummary(). Create twoBookobjects. -
Exercise 3: Add a
getAge()method to the prototype ofBookthat returns how many years ago the book was published.
Solutions:
-
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
``` -
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
``` -
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.
Related topics
Keep learning with adjacent tracks.
Popular tools
Helpful utilities for quick tasks.
Random Password Generator
Create secure, complex passwords with custom length and character options.
Use toolLatest articles
Fresh insights from the CodiWiki team.
AI in Drug Discovery: Accelerating Medical Breakthroughs
In the rapidly evolving landscape of healthcare and pharmaceuticals, Artificial Intelligence (AI) in drug dis…
Read articleAI in Retail: Personalized Shopping and Inventory Management
In the rapidly evolving retail landscape, the integration of Artificial Intelligence (AI) is revolutionizing …
Read articleAI 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 articleAI 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 articleAI in Legal Compliance: Ensuring Regulatory Adherence
In an era where technology continually reshapes the boundaries of industries, Artificial Intelligence (AI) in…
Read article