Learning about OOP in JavaScript
Martin Graham
Posted on December 30, 2021
In which I make a resolution to blog
I am one class into my LaunchSchool experience, and so far it living up to my expectations. Coming from a 'jack-of-all-trades-one-person-IT-department' at my small school, LaunchSchool seems to be offering some much needed polish to my technical background.
JS-120 - Or How I Learned To Stop Worrying and Love OOP
Consider learning about OOP in JavaScript - definitely some ideas that I'm used to, but also some new twists. Props to LaunchSchool's mastery method - if I had a hazy understanding of object references then prototypes would be straight out.
So for today, a brief summary of the OOP patterns (did I mention I'm an amateur - if you are reading this for information...maybe go elsewhere)
- Constructor functions
- OLOO - (objects linking other objects)
- ES6 classes
Constructor functions
function Car() {
//code
}
let myCar = new Car();
Things to note:
- the
new
keyword is crucial - our constructor function won't actually return anything, but invoking withnew
causes the creation of a new object (and it is set as the execution context - i.e.this
within the constructor), and the implicit return of the new object - alsoCar.prototype
is assigned to the[[Prototype]]
property of our new object.
OLOO - Objects Linked to Other Objects
let CarPrototype = {
init(params){
return this;
}
drive(){
}
}
let car1 = Object.create(CarPrototype).init(args);
Here we make a prototype object and use Object.create()
to set up the prototypal relationship - the conventional init
method is used to set initial properties easily. Notice how init
returns this
- absolutely necessary for method chaining to work.
ES6 classes
class Car {
constructor(params){
}
drive() {
}
}
let myCar = new Car(args);
Coming from my dabbling in Java and Python, this is the pattern I am naturally drawn to. Note the constructor
method - invoked with the use of new
, and will be important when subclassing.
Remaining questions I have, in no particular order
- Is one pattern generally used?
- What are the gotcha's for each method - (for instance, subclassing with constructor functions seems to have some quirks)?
Posted on December 30, 2021
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.