Build a Library with es5

IIFE

First, we use an IIEF because we want to invoke a function immediately. This puts the function onto the execution stack. We put parameters are global, and $ because we want to attach properties to the global variable. The $ is jQuery.

Hence, our function looks like this:

We want to execute it immediately so that it gets processed and data gets attached to the global variable. Hence we execute it as a function expression and pass in the window object, and jQuery.

Factory Function

We then create Greetr as a function where we use a utility function called Creator to return instances.

Say we do it this way:

We have a special Creator function that returns instances. However, take note that Greetr is a function with its own prototype object. Creator is a reference to a function. Creator has its own prototype object like this:

So when we get a new Greetr.Creator(…), the instances are pointing to Greetr.Creator’s prototype object.

Now, this is fine and dandy in situations if we were to implement prototypal functions/properties for our Creator prototype, and Greetr prototype separately.

But in our case, we just want to implement prototypal functions/properties for Greetr prototype only. We want all other functions to inherit from our Greetr. Thus, that’s is why we must point our Greetr.Creator’s prototype to Greetr.prototype. That way, any instances created from new Greetr.Creator will inherit from Greetr’s prototype object.

Add our Greetr function to the global object so we can use it

Finally, we attach our Greetr function as a property to the global object so we can use it like so:

Now, let’s show that our diagram and our code match up.

Adding functionality and exposing them

Add private variables

First we add private objects with properties en and zh. This is so that we can assoiative key/value access like so dictionary[“key”] –> value

We want to use it like this:

then get the string phrases back.
Hence we do it like this:

Expose them publicly via prototype object

What we just declared has private access. We expose them by using them in Greetr’s prototype object.

This way, you are declaring function properties for prototype objects. And as we know, all instances and objects that inherit from our prototype objects can access its functionality. Therefore, when we do

we create instances that inherit from Greetr.prototype, and thus, can access its functions/properties
like so:

Source

Chaining

We can also do chaining where we check the language, then just log all the greetings altogether like this:


√ valid language
ni hao, ricky
Nin hao wo de peng you, ricky cao

Simply add the setLang function to update the this.language property, and then change doGreeting and doFullGreeting function where they return the ‘this’ reference. That way, you get the instance object back and then can call another function on that instance.