How to Build your own jQuery like Library

jQuery is one of the most widely use Java Script Libraries and it is a Java Script Object() code that is full functions and methods the have been created by good coder. I have just completed my Java Script course and wanted to post how to build a Java Script Library which makes use of several of the programming techniques that I have learned. I would also like to get some feed back . Here we go.

<!DOC Type html>
<html>

<head>

<title> Building a Library Sturcture and </title>

</head>

<body>
    

<script src = "https://code.jquery.com/jquery-latest.min.js"></script>

<script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.3/underscore-min.js"></script>
    
 
    
</body>

<script>
    
//Take this script and copy and paste into your text editor/compliler or browser console to see how to build your own Library or Framework.
 
                // Framework Structure
// 1) First thing we will want to do is to build safe code by creating a Imediately Invoked Fucntion (IIFE) Expression.  And we will wrap that code by using parenthesis around the entire code and then use parenthesis to invoke the function.  
    
// 2) We want to make sure that the IIFE will accept a global object and a JQuery Object and then pass the object to the "window" & "jQuery" when it is invoked.  This is how we will structure our library.

//(function(global,$){
    
    
    
//}(window,JQuery));
    

//Next we will add our code for the Library and add our greeter function that will return a new object.  And we will use JQuery as an example.  
    
//We want to create a function constructor that will operate like "Greeter" and take a firstname, lastname, and language, and return an new object from the consturctor.
    
//When we build this new object we want to set up some default values for the firstname, lastname, and language.  To do this I will need to use "this" so it will attribute those values to the new object just created.  I can use self = this and then build my object for my parameters/properties.
    
//Now what about the prototypes?  I will use the same prototype as the original object that it was built from.  This is what happen with any function contructor.  
    
//Now we need to expose our new object to the outside word and add it to the global object.  We need to attach it to the global object.  And I will also use a shorthand to invoke my function like jQuery does with the dollar sign.  I will use (G$).
    
// We now need to set up some methods and other properties and where should it be located? They should be written on the original Object and that way will be shared by all newly created objects.   And we can also add some supported languages .
    
    //function constructor
;(function(global, $){
  
    var Greeter = function(firstName,lastName,language){
    
    return new Greeter.init(firstName,lastName,language);
  }  
    
// We can add variables and concepts that are not a part of the return function but can be used by the function since it is within the lexical environment that we have access to due to closure.
    
    //add supported languages
    
    var supportedLangs = ["en", "es"];
    
    
// And we can set up some data that I don't want the developer to have access to.  So lets do some greetings for both english and spanish.  
   
//general greeting
    var greetings = {
        en: "Hello",
        es: "Hola"
                
    };
//formal greeting
    var formalGreetings = {
        en: "Greetings",
        es: "Saludos"
    };
    
    
// Now I have my language and I have my greetings for each language. I can create an option to add some messages when the greetings get loged and  will create a message.  They are objects that I can reference by the name used for english or spanish.
    
    var logMessages = {
        en: "logged in",  
        es: "Incio sesion"
    };
    
    
// Now we can add some prototypes and methods to our Greeter function by simply adding them to our Greeter.prototype and they will be shared with all newly created functions from Greeter.
    
    Greeter.prototype = {
        
        fullName: function(){
            return this.firstName + " " + this.lastName;
        },
        
// Now we can set up a validate function that will check to see if the language choosen is either english or spanish.
        
//this will check the array of supportedLangs look for this.language and if not in array will return -1 which will trigger the function to print "Invalid language" 
    
        
        validate: function(){
        
        if(supportedLangs.indexOf(this.language)=== -1){
            throw "Invalid language";  
        }
        },
        
// will return greeting based on language selected.  greeting[] will be "en" or "sp" and will select either "Hello" or "Hola".
        
        greeting: function() {
            return greetings[this.language] + " " + this.firstName + "!";
        },
   
    
    //will return a formal greeting using full name.
            
            formalGreeting: function(){
                
                return formalGreetings[this.language] + " , " + this.fullName();
            },
        
//Now lets add a greet method that will be chainable and this is the one that  will mostly be use as a developer.  And we can choose if yiu want it to be a formal greeting or not. We will also add a message and log the message to the console.  I will make the method chainable by returning "this".  
        
// And we can also add a function that will change the language on the fly and again also make it chainable.
        
   greet: function(formal){
        var msg;  //if undefined or nullwill be coerced to "false
        if(formal){
           msg = this.formalGreeting();
           }
        else {
        msg = this.greeting();
    }
    
    if(console){
        console.log(msg);
    };
    
// "this" refers to the calling object at execution time and makes the the method chainable
    return this;
         
    },
        
//  And we will add another log function to log if you want to manually make sure something is logged.
        
    log: function() {
        
        if(console){
        console.log(logMessages[this.language] + ":" + this.fullName());
    }
    
    return this;  // to make chainable
    
    },
 
 // And if I want to change the language on the fly I can add a function to change the language.
 
 setLang: function(lang){
    this.language = lang;
    
    this.validate();
    
    return this;
},
        
        
};  //End of Greeter.prototype.  Now all of these methods are inside the object literal Greeter.prototype.
    
    
// Here we set our default values for the newly created Greeter.init.   We will use the "this" function since it will point to the newly created Greeter.init.
    
    Greeter.init = function(firstName,lastName,language){
          
            var self = this;
            self.firstName = firstName || " ";
            self.lastName = lastName || " " ;
            self.language = language || " ";  
        
            self.validate();
    }
    
// set new Greeter function prototype equal to Greeter prototype
    
    Greeter.init.prototype = Greeter.prototype;
    
    global.Greeter = global.G$ = Greeter;
                            
                            
}(window,jQuery));
    
// I want to set up a function that when invoked will give me back an oject like jQuery will do.  And I want to be able to use :
    
    // var  g = G$(firstname, lastname, language);
    

//Now I can create new greeter objects ont he fly and each will share the same prototypes as the original Greeter object.
    
var i = G$("Stevie","Wonder","en");
    
var e = G$("Beyonce","Knowles","es");
    
var n =G$("Whitney", "Houston","en");
    
var r = G$("Sam", "Cook", "es");
    
//I can also use methods that are chainable and call these methods on the fly when calling my newly created objects.  Now lets play a little with the Greet Library.
    
    i.greet();
    
    i.greet().setLang("es").greet(true);
    
    e.greet().greet(true).log();
    
    n.greet().setLang("es").greet(true).log();
    
    e.greet().log();
    
    
    
    
    
    

</script>


</html>
2 Likes

Hi @Imhotep,

This is exceptional.

Building your own library is one of the most valuable projects you can do. It is highly valued in the programming world. This is a great start. You will go a long way if you continue like this Ed.

Cheers!

Thank you Malik. I took the Ivan on Tech course along with the Udemy course Java Script by Anthony Alicia which is considered an Advanced course of Java Script .

JavaScript: Understanding the Weird Parts

An advanced JavaScript course for everyone! Scope, closures, prototypes, ‘this’, build your own framework, and more.

Rating: 4.7 out of 54.7 (40,107 ratings)

156,237 students

Created by Anthony Alicea

Last updated 9/2020

They really complement each other in that the Udemy course is pure Java Script and the Ivan on Tech course includes more on jQuery, html, and css programming. It ended the course with this project on building your own library where you need to apply most of what you learned in the course to develop the library. The course was only $12.99 and the first 3.5 hours of the 12 hour course is free on u-tube called Java Script understanding the weird parts.

1 Like

Hi @Imhotep,

I’ve gone through the course as well and yes it is an advanced course and a very good one too.

Keep up the good work!

1 Like