Monday, June 22, 2015

Closures in JavaScript

Closure in JavaScript are most confusing term, but actually it is most powerful concept of JavaScript. Closure occurs in JavaScript because of functional level scoping. Function inside function can use members of outer function (parent function).

I would like to write 2 most important

  1. The context of an inner function includes the scope of the outer function.
  2. An inner function enjoy that context even after the parent functions have returned.

Let’s discuss one problem scenario, suppose we have one button on the page and now we need how many times button is clicked, we need the count. One simple way of implementation is: use one global variable and increment that variable on button click. This is easy but Global variables are not good to use, because same variable name might be present in the application. It is never recommended to use global variable in JavaScript. One good solution to this is to use functional level scoping of JavaScript and create Closure. Closure in JavaScript are caused due to function level scoping.

Below is one example of closure which is used to get one incremented number every time.

    var getCount = (function () {
        var counter = 0; // parent function variable which is accessible in child function
        return function () {
            return ++counter;
        };
    })(); // self executing function 

The output of this function when called will be as shown below:

Saturday, June 20, 2015

Private functions and variables in JavaScript..!

Private function or properties we know very well in programming language like Java, C#. Is it possible to achieve this in JavaScript? Yes..!

If you want to know more about Object oriented concepts in JavaScript then please first go through this post: OOPs in JS

In JavaScript Functions are so powerful to build OOPs and modular concepts. Following concepts are implemented using Function only in JavaScript:

  1. Method
  2. Class
  3. Constructor
  4. Module

Below code shows the code which create class MyClass and it has private members:

    function MyClass(a) {
        var count = 3; // private member

        // this check function is private function
        function check() {
            if (count > 0) {
                count--;
                return true;                
            }
            else {
                return false;
            }
        }
        this._a = a;
        this.get = function () {
            if (check()) { // use of private function
                return this._a;
            }
            else {
                return "Thullu"; // after invoking get method 3 times in the object this else will be executed
            }
        }
    }

In the above code variable, count is private as any object created from MyClass will not have this variable similarly function check() is private function as this function is not part of this in the MyClass. When we create an object of MyClass using new keyword this is returned. This concept is possible in JavaScript because of lexical scoping (functional scoping).

When we create object of this class MyClass, and call the get method more than 3 times:

I would like to write few points regarding new keyword.

  1. When a function is called with the new operator, a new object is created with prototype members and assigned to this.
  2. Above statement is true only if there is no explicit return value in the function. If explicit return is present in Class (function), then same return will be assigned to the object.

I would like to give here one more example with very basic functionality like in all OOP languages we have. We declare private field and then use public properties to expose the private field, in more formal and OOPs way we create Get and Set method to update private field or retrieve private member of class.

Same get and set functionality for private variables in JavaScript we can achieve as shown in below example:

 // private class with get and set methods
    function MyClass() {
        var _privateField = 0; // It is private field as it is not part of "this"
        this.GetPrivateField = function () {
            return _privateField;
        };
        this.SetPrivateField = function (value) {
            _privateField = value;
        };
    }
Following is the console output using above MyClass object:

Sunday, June 14, 2015

JavaScript function as an Object


If you have experience in JavaScript then I am sure you have heard about functions in JS are first class object. In this post I will try my best to explain about functions in JS as an object.

There are many ways to create functions in JS, you can get to know about this in this post: Number of ways to create function

We can add property in any function as we add in any object:

    var MyObj = {}; // creating object
    MyObj.prop1 = "value1"; // Added one property
    console.log(MyObj.prop1); // logs: value1

    // creating function
    function MyFun(arg1, arg2) {
        return arg1 + arg2;
    }

    // adding property in function, and function behave as an object
    MyFun.property1 = "funPropValue1";
    console.log(MyFun.property1); // logs: funPropValue1 
Above code shows that function behave in same way as object while adding new property in function.

Pass function in another function as an argument

In below code a method is passed in function argument, and it executes successfully:
    var MyObj = {};
    MyObj.prop1 = "value1";
    MyObj.logValue = function (value) {
        console.log(value);
    }

    function MyFun(arg1, argFun) {
        var myVal = 1;
        myVal++;
        argFun(myVal);
    }

    MyFun(12, MyObj.logValue); // logs: 2
As we can perform operations similar to object in functions we can say that functions are first class object in JavaScript.

Saturday, June 13, 2015

Number of ways in JavaScript to create functions

Functions in JavaScript are first class object, we can add properties in functions as we add in any object of JavaScript. We can pass function as argument in any function as we pass any object or variable. There are 3 ways we can define function in JavaScript.

  1. Function constructor
  2. Function statement
  3. Function expression

1. Function constructor

Create function using Function constructor as shown below, I am creating one simple function for addition of 2 numbers:
var add= new Function('x','y','return (x+y);');
In this type of function creation, last parameter is the function body. we can pass as many parameters we want. In below example I am passing 3 parameters.
var add= new Function('x','y','z','return (x+y+z);');

2. Function statement

This is the very common or we can say general approach to create function in JavaScript and similar to other programming languages.
function add(a,b){
 return (a+b);
}
This approach is very simple and easy to understand for new developer of JavaScript also.

3. Function expression

In this approach function is declared in a variable, it is like one expression in JavaScript.
var add = function(a,b){
 return (a+b);
};
There is one more variation of this approach which is called named function expression. As you noticed in above function there is no name given after function keyword, but can give name also as shown below:
var add= function addFn(a,b){
 return (a+b);
};
We can give any name after function and both codes (expression and named expression) behavior is same.

Sunday, June 7, 2015

AJAX call in AngularJS for cross domain service using JSONP

It is very easy to set up AJAX call in AngularJS with $http.get(). Similarly in Angular cross domain request is also very easy using JSONP, below code shows how to set up AJAX call for cross domain using $http.jsonp():

(function () {
    var App = angular.module("AngularCrossDomain", []);
    App.controller("AppController", function ($scope, $http) {
        $http.jsonp('<Your Service URL>?callback=JSON_CALLBACK')
            .success(function (data) {
                console.log("pass");
                $scope.value = data; 
            })
            .error(function (data) {
                console.log("failed");
            });
    });
})();

Object Oriented Programmings: Prevent/Allow Inheritance and Prevent/Allow Instantiate

Hello friend,

In this post I am explaining about 4 scenarios which might occur in any real time project or required while implementing an application. Coding is done in C#. but I am sure similar concepts are available in other languages as well like Java.

  1. Implement class which is allowed to inherit and allowed to create instance
  2. Implement class which is allowed to inherit but not allowed to create instance
  3. Implement class which is not allowed to inherit and allowed to create instance
  4. Implement class which is not allowed to inherit and not allowed to create instance

1. Implement class which is allowed to inherit and allowed to create instance

This is the simplest implementation, just create a public class and it will be allowed to inherited and also allowed to create object of this type of class.
    class Class1
    {
        public virtual void Method1()
        {
            Console.WriteLine("In class 1");
        }
    }
    class Class2 : Class1
    {
        public override void Method1() {
            Console.WriteLine("Method1 In class 2");
        }
        public void Method2()
        {
            Console.WriteLine("In class 2");
        }
    }
    class Program
    {
        static void Main(string[] args)
        {
            Class2 c2 = new Class2();
            c2.Method1();   // Print: Method1 in class 2
        }
    }

2. Implement class which is allowed to inherit but not allowed to create instances

To prevent instances of a class is very common feature required for any application. I would like to add one real scenario here in which there is requirement to prevent creating object of class. Suppose we want create one application where we manage employee data for an organization and this organization has 2 types of employee, first Permanent type and second Contract type. There are many properties and behaviors which are common in both type of employees, so we will create one base class to write all the properties and methods. Now if we created this base class with just simple public access modifier, then any one (developer) can create instance of this base class, while conceptually developer should only allow to create object of Permanent employee class or Contract employee class because base employee is not a real employee (there is no existence of only employee in real world, an employee is Permanent employee or Contract employee in this organization1). So to prevent developer creating object of base Employee class, we can use concept of abstract class. Abstract class can not be instantiated, but can be inherited. All the abstract methods of abstract class must be overridden by derived class. Abstract class can also have methods which are not not abstract and full body declaration. If we try to create object of abstract class, compiler will show error as shown below:
We can inherit abstract class easily and implement abstract methods in derived class, as shown below:
abstract class Class1
    {
        public abstract void Method1();
    }
    class Class2 : Class1
    {
        public override void Method1() {
            Console.WriteLine("Abstract method body declaration");
        }
    }
    class Program
    {
        static void Main(string[] args)
        {
            Class1 c1 = new Class2();
            c1.Method1(); // Print: Abstract method body declaration
            Console.Read();
        }
    }
Interface also prevent instantiate, you can not create object of an interface. The interface methods must be overridden while abstract class methods can be overridden.

3. Implement class which is not allowed to inherit and allowed to create instance

C# provide sealed modifier which prevent any class to inherit. You will get error if try to inherit sealed class as shown below:
Below code shows how to use sealed modifier and we can create object of sealed type class easily:
    sealed class Class1
    {
        public void Method1()
        {
            Console.WriteLine("In class1");
        }
    }
    class Class2
    {
        public void Method1()
        {
            Console.WriteLine("In Class2");
        }
    }
    class Program
    {
        static void Main(string[] args)
        {
            Class1 c1 = new Class1();
            c1.Method1();
            Console.Read();
        }
    }
Java provide final modifier to prevent inheritance.

4. Implement class which is not allowed to inherit and not allowed to create instance

To prevent inheritance and instantiate both we can use private constructor of that class. If class constructor access modifier is private then it can not be instantiate as well as inherit from any class as shown below:
Private constructor is used in many application, for example we want to create Utility class and methods of this class should be available directly without creating object of this class, below code shows how to do this:
class Class1
    {
        private Class1()
        {
        }
        public static void Method1()
        {
            Console.Write("class1 static method");
        }
    }
    class Class2
    {
        public void Method1()
        {
            Console.Write("In Class2");
            Class1.Method1();
        }
    }
    class Program
    {
        static void Main(string[] args)
        {
            Class2 c2 = new Class2();
            c2.Method1(); // Print: In Class2 class1 static method
            Console.Read();
        }
    }
Please feel free to give any suggestion if I have written any thing incorrect.


Tuesday, June 2, 2015

JavaScript's 9 Native Object Constructors

In JavaScript almost everything is object or act like object. Most values (excluding primitive values) involve object being created or instantiated from constructor function. An object returned from the constructor is called an instance. JavaScript uses native constructor to build everything.

JavaScript has nine native constructors to achieve everything in JavaScript programming language. For example functions are objects created from Function() constructor. String(), Boolean() and Number() constructors are not only construct objects but also provide primitive value for string, Boolean, and number.

  • String()
  • Boolean()
  • Number()
  • Object()
  • Function()
  • Array()
  • RegExp()
  • Error()
  • Date()

To remember these 9 native constructors I have created one acronym "SBN OF A RED". This acronym is easy to learn and also in relevant groups.

To create a number variable in JavaScript there are 2 ways:

  1. var iMyNumberPrimitive = 9;
  2. var iMyNumberObject = new Number(9);
First method is to just create primitive value for number, string or Boolean. Second method create complex object with primitive value. You can see below the behavior of such declarations with console:

Same way we can create other type of variables also. It is good practice to use simple primitive variable declaration always if we want normal variables operations, because JavaScript create complex object when you use constructor and will have many other properties associated with variable.