Advanced JavaScript 101: Prototypes — Adding functions to Object Constructors within IIFEs

Andrew Neidley
May 12, 2018 · 2 min read

It took me going back, practicing concepts, and building a simple console.log trivia game to comprehend and thus fully appreciate the concept of Closures as well as the three tools specified in the title to this article.

Constructors within IIFEs (immediately-invoked function expressions) with Prototypes added.

When all used together think of it like a factory, surrounded by an invisibility dome, that creates people and defines the actions those people can perform…

Let’s break each one down:

(1)Immediately-Invoked Function Expressions

…long name, not as scary as they sound…

are expressions as the name suggests that create code privacy and thus reusability when wrapped around any scope of code.

(2)Constructors

are functions that create instances of an object. Like a factory that creates People objects. (not saying people are objects…ya know, I’m just gonna move on) They are known as classes in other programming languages, such as Ruby.

(3)Prototypes

introduce the ability to add a function, that can be called at any time on any instance of a constructor’s created object.

Huh?

Below, you can see an example of a prototype function/method to calculateBirthYear that is added to and exists on a Person constructor and thus every instantiated person object. The ability to add functions after the fact to a constructor is an essential tool in any JavaScript coder’s toolbox.

To further clarify, Prototypes are functions that exist on Constructors, but are added after & outside the initial Constructor ’s line(s) of code. It is good practice and practical not to define functions/methods directly within the constructor, so prototypes are used.

//start IIFE
(function () {
//Person Constructor
function Person(name, age) {
this.name = name;
this.age = age;
}
//Sample people
var personOne = new Person('Luke', 24);
var personOne = new Person('Leia', 24);
//Prototype added to Person Constructor
Person.prototype.calculateBirthYear = function(currentYear){
//do something
console.log(currentYear - this.age);
}
//Call function
personOne.calculateBirthYear(2018); //logs to the console: 1994
//close IIFE
})();
IIFE, Constructor, and Prototype printing to the console calculateBirthYear in vanilla JavaScript

Simple enough? Did I blow your mind?

IIFEs, Constructors, and Prototypes.

Until next time,

Andrew Neidley


For more about me and all things code, please don’t hesitate to visit my website.

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade