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: