Constructors, Classes and Closures

These concepts relate to Object Orientated Programming. I tend to forget or muddle them up so I am hoping writing this will help me get my terminology straight!

Constructors

Constructors are functions that create new objects. They should be distinguished by the use of a CAPITAL letter at the start of their name. We can define properties it will have by saying:

this.<property> = <value>

To make a new instance using the constructor we use the NEW operator:

We can specify what we want the properties to be by passing through some arguments to the function:

Objects created with constructor functions are considered instances of the constructor:

Properties that are defined on the instance Object, ie they have their own separate properites are called own properties.

You can use the following method to check if there is a certain own property: dog.hasOwnProperty(numLegs);

Prototypes

Prototypes are the recipe for creating objects.

If we have a collection of dogs we can be sure that every one has 4 legs (in this world, there are no accidents) so instead of defining the number of legs on each instance of dog we can instead assign it to the prototype:

So objects have thier own properties and prototype properties.

We can populate the prototype like any object:

Watch out though, the constructor property will be lost so manually define it by including the property:

Prototypes get inherited from the constructor function that created it. You can test if the prototype comes form a certain source by using :

The Prototype chain

All objects, with a few exceptions have a prototype and the protype itself has a prototype.

Object.prototype.isPrototypeOf(Dog.prototype)

The core of object oriented programming is using inheritance so you don’t repeat yourself.

Objects up the Chain are supertypes Objects down the chain are subtypes 
terrier ------ > dog -----> Animal

To set something for inheritance it’s a good idea to use Object Create:

Note that the Dog’s constructor property will be set to animal.

You can set this manually by doing:

You can have methods on subTypes that are unique to them.

So overall it’s a 3 step process:

  1. Set the Dog.prototype to the Animal.prototype
  2. Set the Dog.prototype.constructor = Dog;
  3. Add the method to the prototype via

You can override parent methods by making another with the same name that overrides the parent method.

Mixins

If you have two objects that should share SOME properties but not others you can use a mixin function to give a payload of properties to the relevant objects:

Closures

The infamous Closure, not as scary as it first appears. Let me simplify it. First if you have an object you will have properties:

function Person() { passportNumber = 344432444; }

Currently passportNumber is public, so any part of the code can just do <person>.passportNumber and change it. This can be a problem in big codebases. So we can make it only available within the object’s scope by setting the variable inside the function:

However, now we can only access passportNumber within the object’s scope right?

That’s where we need a closure!

A closure is a method to the object which has the job of fetching ,an otherwise private, property. The method will have access to the Object scope and can return it when asked from outside the Object scope.

This is not quite right but should give you the gist of it:

I always imagine a closure as a Personal Assistant who can give you the information you asked for from the Boss’ office, but not letting you otherwise access the Boss’ Office…. well it works for me.

Immediately Invoked Function Expression

Lets just make it clear that you can run an anonymous function as soon as it is declared. The following function is pretty immediate:

But you can turn it into a IFFE by using a quirk of the language:

(function (){ console.log("A hello to you") })();

Basically you wrap the function in () and then add another pair at the end to invoke.

Combine IIFEs and Mixins to Make Modules

IIFEs can be used to create a package called a which can contain a number of mixins.

(oops I did a bad markdown thing!)

We can add a method to the prototype by doing:

Classes mean we don’t have to worry about the prototype in the same way. So the example refactored using classes is like this:

https://gist.github.com/899023de559794ca192e5461f14b81c5

Hooking up two constructor functions is a pain in ES5. So we have two constructor functions, but as Toyota is a Car we want to create that link between them. To do this we can do the following.

Note that the constructor method is where we do any initialisation and you don’t need to split methods by commas as in objects.

How do we have a subclass Toyota from Car?

However we need to get the Car’s constructor method so we need to use:

super(options) //arguments to pass up

This tells Toyota constructor function to go and grab the parent Constructor function. So the finished article looks like this

Conclusion

Constructors, Classes and Object Oriented programming comes into its own once you start building more complex applications. It allows us to separate concerns without repeating code needlessly.

The drawback, which really isn’t a valid one, is that it forces you to think of the design of the overall application and how things can related to each other and share methods. That’s a good thing but when I was a complete beginner you just tend to create things here and there as and when you need them. I don’t think you need to plan every little thing, thats what refactoring is for.

In the meantime, it is important to at least be familiar with these concepts as a lot of libraries and frameworks (looking at you, React) rely on them to work and kinda expect you to be comfortable with them.

Classes get a bit of a bad rap as just being syntactical sugar of prototypal inheritance but I think that’s a bit mean. It makes inheritance much more easier to deduce and the usage is cleaner to look at. Apparently its not as good as other language’s implementations at least we can agree its going in the right direction.

All about the things I bumble into as a Web Dev