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
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, student
is an object with properties name
, age
and a method greet()
. this.name
refers to the name
property of the student
object.
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
.
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
.
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.
```
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.
Exercise 1: Create a Person
object with properties firstName
, lastName
, and a method getFullName()
.
Exercise 2: Create a Book
constructor with properties title
, author
, year
and a method getSummary()
. Create two Book
objects.
Exercise 3: Add a getAge()
method to the prototype of Book
that 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.