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.