Part 1: The JavaScript OLOO Pattern Explained (with pictures)

  • Part 1 covers Prototype Inheritance and delegation in JavaScript with the OLOO pattern
  • Part 2 deals with the Pseudo-classical pattern — a combination of constructor functions and prototypes that create objects in JavaScript

Traditional Class-Based Objects

We will be expanding on Software Engineer Mehdi Maujood’s brilliant chair object metaphor:

class Chair
def initialize(width, height)
@width = width
@height = height
end
end
my_chair = Chair.new(50, 45)
class Chair
def initialize(width, min_height)
@width = width
@min_height = min_height
end
end
class DeskChair < Chair
def initialize(width, min_height, max_height, wheels)
super(width, min_height)
@max_height = max_height
@wheels = wheels
end
end
my_chair = Chair.new(50, 45)
my_desk_chair = DeskChair.new(50, 45, 52, 5)

JavaScript Prototypes

Continuing with Mehdi Maujood’s chair metaphor — when it comes to prototypes, we don’t create blueprints or classes, we just create a chair object. Imagine chopping up some wood and building a chair out of it. This is a fully functional chair object and can work as the prototype for future chair objects:

let myChair = {
width: 50,
height: 45,
};
In JavaScript objects don’t need classes
let myChair = {
width: 50,
minHeight: 45,
};
let myDeskChair = Object.create(myChair);
myDeskChair.maxHeight = 52;
myDeskChair.wheels = 5;
let myChair = {
init(width, height) {
this.width = width;
this.height = height;
return this;
}
};
let anotherChair = Object.create(myChair).init(40,60);
p my_desk_chair#<DeskChair:0x000055e0cfa1fdc8 
@width=50, @min_height=45, @max_height=52, @wheels=5>
console.log(myDeskChair);{ maxHeight: 52, wheels: 5 }

The Prototypal Chain: Inheritance & Delegation

If you looked close enough you might have noticed that the Ruby desk chair contained all its properties: width, min_height, max_height and wheels whereas our new JavaScript desk chair object only contains maxHeight and wheels. That’s strange…didn’t we ‘duplicate’ our original chair? Shouldn’t it have all the properties from our original chair prototype?

console.log(myDeskChair);    // { maxHeight: 52, wheels: 5 }myDeskChair.width;           // 50
myDeskChair.min_height; // 45

Conclusion

This Object creation pattern is known as OLOO or “Objects Linking to Other Objects”, which is at the heart of how objects really work in JavaScript. Historically speaking OLOO was introduced after the Pseudo-classical pattern, in an attempt to return to the true nature of JavaScript objects, prototypes and delegation.

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store