Object-oriented programming (or OOP) is a paradigm or pattern of programming whereby the solution to a programming problem is modelled as a collection of collaborating objects.
An object is an entity that possesses both state (or properties or attributes) and behaviour. Put another way, an object encapsulates data and the functions that operate on that data. The data is usually hidden from other objects so that the only way to affect the data is through the object’s functions (or methods)
- Medium.com - What is Object-Oriented Programming
- Medium.com - A Simple Explanation of OOP
- freeCodeCamp.com - How to explain object-oriented programming concepts to a 6-year-old
- Video - Object-Oriented Programming in 7 Minutes
- Object Literal
- Function (Factory Pattern)
- Constructor Function
- Constructor & Prototype Pattern
- ES6 Class
let coco = {
name: "Coco",
age: 10,
makeNoise: () => {
console.log('UhhUhhUhh')
}
};
let ophelia = {
name: "Ophelia",
age: 6,
makeNoise: () => {
console.log('Meooow')
}
};
let tweety = {
name: "Tweety",
age: 7,
makeNoise: () => {
console.log('Chirp Chirp')
}
};
- A lot of duplication (keys) = Not DRY
- If you change one object's methods you have to change it on all objects to achieve same functionality
function createAnimal(name, age, noise) {
var obj = {};
obj.name = name;
obj.age = age;
obj.noise = noise;
obj.makeNoise = function() {
console.log(noise)
};
return obj;
}
let coco = createAnimal('Coco', 10, 'UhhUhhUhh');
let ophelia = createAnimal('Ophelia', 6, 'Meooow');
let tweety = createAnimal('Tweety', 7, 'Chirp Chirp');
- Less duplication
- Have to create empty object first
- Have to return object
- Methods are still not shared across all objects
// Convention is to uppercase first letter of constructor function
function Animal(name, age, noise) {
this.name = name;
this.age = age;
this.noise = noise;
this.makeNoise = function() {
console.log(this.noise)
};
}
// "new" Keyword
let coco = new Animal('Coco', 10, 'UhhUhhUhh');
let ophelia = new Animal('Ophelia', 6, 'Meooow');
let tweety = new Animal('Tweety', 7, 'Chirp Chirp');
- Even less duplication
- Methods are still duplicated across all objects
This is the most common used pattern before ES6 class syntax came around.
function Animal(name, age, noise) {
this.name = name;
this.age = age;
this.noise = noise;
}
// Methods are moved outside of constructor onto the "prototype" object
Animal.prototype.makeNoise = function() {
console.log(this.noise);
}
// Instantiation stays the same with "new" Keyword
let coco = new Animal('Coco', 10, 'UhhUhhUhh');
...
The latest and greatest...
class Animal(name, age, noise) {
constructor {
this.name = name;
this.age = age;
this.noise = noise;
}
// method within class
makeNoise() {
console.log(this.noise);
}
}
// Instantiation still the same with "new" Keyword
let coco = new Animal('Coco', 10, 'UhhUhhUhh');
...