Click here to Skip to main content
15,879,184 members
Articles / Programming Languages / Javascript
Tip/Trick

Bind Object With Functions in JavaScript

Rate me:
Please Sign up or sign in to vote.
5.00/5 (1 vote)
1 May 2013CPOL2 min read 13.8K   4   6
This tip will show the power of closure in OO JavaScript

Introduction

This is a very simple tip to show how can we increase the power of Object Oriented JavaScript with the help of closure. I assume that everyone who reads the tip has a basic idea about Closure.

Using the Code

As I mentioned, this is simple tip so I will try to make my examples very simple and understandable.

To call a JavaScript function, we can use function.apply(context,arguments).

Consider the below example. Here, I am trying to hold the reference of the Add and Subtract functions to my Calculator objects to add and sub properties respectively so that on $(function(){}) (document ready), I can access those two by calling Calculator.add() or Calculator.sub(). Look at the code below and think, will it satisfy our goal or not? The answer is: No. Rather, holding the function it will execute itself first on document ready give alert of 30 and 10 . Surprise!!!!! No problem, I will explain to you.

JavaScript
<script type="text/javascript">
       function bind(context, fn, args) {
           return fn.apply(context, args || []);
       }
       function Add(a, b) {
           alert(a + b);
       }
       function Subtract(a, b) {
           alert(a - b);
       }
       $(function () {
           // Handler for .ready() called.
           var Calculator = {
               add: bind(this, Add, [10, 20]),
               sub: bind(this, Subtract, [20, 10])
           };
       });
   </script>

This code actually generates the following output at run time:

JavaScript
var Calculator = {add : Add(10,20), sub: Subtract(20,10)};

It gives a clear indication that while Calculator object initializes itself on document ready, it's actually assigning the output of Add and Subtract method to Calculator.add and Calculator.sub properties respectively, rather than wrapping the functions to it. That is why we are facing the alert .

So now, how can we hold the function to our Calculator object? Look at the below example - it will satisfy our requirement. Run the below code and feel the difference:

JavaScript
<script type="text/javascript">
        function bind(context, fn, args) {
            return function () {
                fn.apply(context, args || []);
            }
        }
        function Add(a, b) {
            alert(a + b);
        }
        function Subtract(a, b) {
            alert(a - b);
        }
        $(function () {
            // Handler for .ready() called.
            var Calculator = {
                add: bind(this, Add, [10, 20]),
                sub: bind(this, Subtract, [20, 10])
            };
        });
    </script> 

Points of Interest

Did you notice the trick? Yes, the below code makes the difference. The magic of Closure, it gives you function scoping.

JavaScript
return function () {
               fn.apply(this, args || []);
           }

Actually the Calculator object here plays a different role while it is initialing at run time, it generates the below code:

JavaScript
var Calculator = {
                add: function () { bind(this, Add, [10, 20])},
                sub: function () { bind(this, Subtract, [20, 10])}
            };   

It wraps the function to its property rather than assigning its value.

Now you can call your functions through your Calculator object like this:

JavaScript
Calculator.add(); 

Calculator["sub"]();

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Bangladesh Bangladesh
I am a Sr.Software Engineer at Brain Station -23. I have 5+ years of work experience in .Net technology. I strongly believe that before software can be reusable it first has to be usable.

My contact info :

mfrony2003@yahoo.com
mfrony2003@hotmail.com

LinkedIn
http://www.linkedin.com/profile/view?id=106671466&trk=tab_pro

Comments and Discussions

 
QuestionMy vote of 5 Pin
PPS Gusain13-May-13 8:52
PPS Gusain13-May-13 8:52 
AnswerRe: My vote of 5 Pin
Faisal(mfrony)13-May-13 21:11
Faisal(mfrony)13-May-13 21:11 
QuestionRe: Code does not work - It works mostly my Vote of 4 Pin
PPS Gusain11-May-13 5:35
PPS Gusain11-May-13 5:35 
The code does work mostly.
Calculator.add() works but Calculator.["sub"] does not work at least in IE10.
So my vote of 4
Thanks for the tip
P. P. S. Gusain
AnswerRe: Code does not work - It works mostly my Vote of 4 Pin
Faisal(mfrony)12-May-13 21:46
Faisal(mfrony)12-May-13 21:46 
GeneralRe: Code does not work - It works mostly my Vote of 4 Pin
PPS Gusain13-May-13 8:27
PPS Gusain13-May-13 8:27 
Questioncode does not work Pin
PPS Gusain9-May-13 3:27
PPS Gusain9-May-13 3:27 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.