The Pseudoclassical Past ES5
Before jumping into ES6 and learning the class keyword I thought it was important to understand the pseudoclassical ES5 style for creating classes. I call it pseudoclassical because even though JS is an objct Oriented language it didn’t have a formal way of creating class constructors like most languages, hence the term pseudoclassical.
Components of a Pseudoclass
Constructor
For the constructor I normally capitalize the function name just to denote its a constructor.
function Bike(gears,style) {
this.gears = gears
this.wheels = 2
this.style = style
}Methods
These allow you to call methods on any instance of bike()
Bike.prototype.isExpensive = function() {
console.log(this.style !== 'cruiser')
}
Bike.prototype.countGears = function() {
console.log('I has',this.gears,'gears')
}To Create an instance of a Pseudoclass
var myBike = new Bike(12,'mountain')Now if I run the methods in this instance of Bike:
console.log(myBike.wheels) // this will print out 2
myBike.isExpensive() // Will log out true
myBike.countGears() // Will log out I has 12 gearsWhat the new Keyword does
It turns any function call into a constructor call, and then 4 things will occur:
-
Brand new empty object created
{} -
Object gets linked to different Object
-
New Object gets bound as this keyword for functon call
-
If no return then implicitly return
this
// If you were to build the new keyword as a function
// you will have to change the name to really run this as
// new is a key word
function new(constructor,args) {
var obj = {}
Object.setPrototypeOf(obj,constructor.prototype)
var argsArray = Array.prototype.slice.apply(arguments)
return constructor.apply(obj,argsArray.slice(1)) || obj
}
var myBike = new(Bike,12,'mountain')
console.log(myBike.wheels) // this will print out 2
myBike.isExpensive() // Will log out true
myBike.countGears() // Will log out I has 12 gearsClasses in ES6
Classes are mainly just syntactic sugar for example:
function Foo(name) {
this.name
}
Foo.prototype.bar = function() {//...}
Foo.protoype.baz = function() {//...}
// is functionally the same as
class Foo {
constructor(name) {
this.name
}
bar () {//...}
baz () {//...}
}There are some more things you can do with classes such as
class Foo {
constructor(name) {
this.name
}
bar () {//...}
baz () {//...}
}
class Doo extends Foo {
constructor(type) {
super(name)
this.type = type
}
showType () {//...}
}Here extends is used to make Doo a child of Foo and super is used to call functions on an objects parent. Click on the links for more info.
Recommendations
To read more on es6 classes or really anything I discussed here. I highly recommend checking out Kyle Simpson’s You Don’t Know JS Series, Kyle Simpson’s Front-End Masters video’s, or the FunFunFunction YouTube channel as they explain things way better than I can.