A Guide before Learning a New JavaScript Framework

This tutorial is aimed at Web Developers, planning to take up a JavaScript framework, it is assumed that the developer is already familiar with the basic JavaScript usage, as we will be jumping into intermediate aspect of JavaScript; though at certain points I will make references to basic foundation knowledge.

JavaScript Frameworks are codes, functions, paradigms written in ways to help developers create short codes with maximum compatibility. They are structured in such a way that non-JavaScript users can easily grasp the codes with little lines; However due to the fact that developers are more familiar with the framework than the language itself, coders often get frustrated especially when they get errors that offer little or no explanation. We will cover certain aspects of JavaScript and good practices to adhere to.

HTML DOM

According to Sang Shin he defined “DOM” as

The HTML DOM defines a standard set of objects for HTML, and a standard way to access and manipulate HTML documents.

All HTML elements, along with their containing text and attributes, can be accessed through the DOM.

The contents can be modified or deleted, and new elements can be created.

The HTML DOM is platform and language independent. It can be used by any programming language like Java, JavaScript, and VBScript

The Document Object Model (DOM) is a powerful tool for manipulating Documents and elements in the browser, however DOM Manipulation is quite tricky and complex and various client browser support certain features and some don’t, which is where frameworks come in, they handle the compatibility issue leaving you to focus on the logical layer. However a good insight into DOM is worth your time.

Understanding Objects and Functions

JavaScript is quite confusing especially when it comes to defining Functions and Objects, languages like PHP, Ruby and C defines functions as a method (performing an action). However in JavaScript it is quite different, the single tip i will give you to memorize is that

EVERY FUNCTION IS AN OBJECT

Functions in JS are first class objects according to Sang Shin.

Functions can contain variables and function (closure) like Objects. Functions can perform the same operations as objects. A function is a type of Object.

//Creating a Simple Function in JS
function MyFunc(value)
{
    alert(value);
}
//Now Lets’s Add Some Variables like An Object Does
function MyFunc(value)
{
    if(value)
    {
        this.innervar=value;
    }
    return this.innervar;
}
//Another Way of Calling a Function
var Test=function(value)
{
    alert("I am a function");
}
//Calling the Function
Test(); //I am a function
There are times we might need to create anonymous functions, these are functions that are self-invoking, they invoke immediately. They are usually used as callbacks or associated with events handlers. Jquery use anonymous functions especially in the creation of plugins.
(function(){
    alert("I will Run first before any function if not attached to any event handler");
})

What the Hell is – “THIS”

Unlike other programming languages this in PHP, C, C++, Java refers to the Class, however in JavaScript carrying that knowledge will throw you into an abyss of frustration and confusion. At times you might begin to doubt your intellect but don’t; the this keyword in JS refers to an Object calling a method.

var car=new function()
{
    car.model="toyota";
    // this adds a variable ”model” to the car Object

    this.color="red"
    //However at this level this refers to the Car Object so this is far more preferable
}
When dealing with this, especially in Plugin creation and DOM Querying it is advisable to store the this to a variable for easy reference.

Knowing Your Objects

For the sake of simplicity, I will not jump into an in-depth explanation of Objects because JavaScript is basically all about Objects, a brief introduction and use will suffice. Objects are easy to create however in certain languages Objects cannot have dynamic properties added to it, but JS does.

//Creating an Object the traditional way
var phone=new Object();
phone.name="Android";
phone._isFlashSupported=true;
phone._3dEnabled=true;
phone.storeName="Android Marketplace";
//Calling the Phone name is as easy calling
alert phone.name //Android
Another Style using JS Template
function Phone(name,flash,hardware,appstore)
{
    this.name=name;
    this._isFlashSupported=flash;
    this._3dEnabled=hardware;
    this.appstore=appstore;
}
var Nokia=new Phone("Symbian",true,true,"OviStore");
console.log(Nokia.name); //prints Symbian
Using the JSON Format
var Apple={
    name:"IOS Apple",
    isFlashSupported:"Never Will",
    _3dEnabled:true,
    appstore:"AppStore"
}
var apple=new Apple(); //throws an Error Apple has no Constructor

//Proper use
console.log(Apple.name); //IOS Apple
Serious Note should be taken into consideration unlike the others, the JSON is an Object while the others are function Objects meaning you cannot call Apple(); JSON Can be easily extended [Mixin]
Apple.name="Apple OS";
console.log(Apple.name); //it overwrites the previous IOS,

Understanding Prototypes

Prototype is one of the most vital and important aspect of JavaScript, prototype allows user to extends [Function Objects]. Prototype is very essential especially to developers hoping to create plugins, frameworks and reusable Objects. Without much words allow me to proof the power of prototype.

//We will create a function to be extended to all String Objects
function countV(){
    //store Object
    var StringObj=this; 
    //Because countV is a function that will extend the String Object this will refer to the String itself if
    //Our Json Object to Hold Data this is more efficient as you can return multiple results in one Object
    var letter={vowel:0,consonant:0};
    //Our loop
    for(var i=0; i < StringObj.length; i++) //Remember StringObj holds the String Object
    {
        //This will compare the characters and determine which is consonant and vowel by updating the Json Object
        if(StringObj[i] == "a" || StringObj[i] =="e" || StringObj[i] =="i" ||StringObj[i] =="o" || StringObj[i] =="u")
            letter.vowel++; //increment the data by 1 if vowel found
        else
            letter.consonant++; //increment the data by 1 if consonant found
    }
    //do not use this.letter because this means String and letter is not an Object of String its an inner variable so we simple use letter
    return letter;
}
//This Injects the function into the String Object so any String Object will be able to call count
String.prototype.count=countV;
//Testing Our function
var r=new String("Welcome");
console.log(r.count()) //returns the letter Json data
console.log(r.count().vowel) //returns vowel

Grasping Closure

The Closure concept is quite confusing at times and can be difficult to grasp. Closures are inner functions that use variables that resides outside of the function.

var message="pc guru at Nairaland";
function sayMessage()
{
    function _innerClosure()
    {
        return message; //returns message to the function _innerClosure
    }
    return _innerClosure(); //returns the return value from innerClosure to sayMessage attempt removing the return here
}
with closure you can create a main function which will emulate the class, add some JSON variables and some inner functions they will act like private methods because closures only exist within the enclosed function.

What About Classes and Inheritance?

Yes, classes and inheritance are another vital and important feature worth knowing, however many frameworks have better ways of making classes and inheritance much more easier and saner than JavaScript’s way. Examples of such frameworks are the “Dojo Toolkit”, “Mootools” and any other framework that provides that interface, with this guidelines you will have a good foundation on some aspect of JavaScript as most will aid you to better understanding what framework to use.

However as at Jquery 1.4 there are no in-built methods to emulate classes and inheritance except to extend the Jquery Object itself, though such a plug-in should exist, as the jquery community strives hard to come up with plugins to strengthen the toolkit.

Web developer,Php Zend and Javascript Dojo coder,and am in love with Enya. And lover of dark arts and alcohol. I hope to learn C php extensions and NodeJS. and i can't live without a PS3 :D

Leave a Reply

Your email address will not be published. Required fields are marked *