Click here to Skip to main content
11,575,925 members (58,516 online)
Click here to Skip to main content

Tagged as

Bind Object With Functions in JavaScript

, 1 May 2013 CPOL 6.2K 4
Rate this:
Please Sign up or sign in to vote.
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.

 <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:

 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:

<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.

 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:

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:

Calculator.add(); 

Calculator["sub"]();

License

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

Share

About the Author

Faisal(mfrony)
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

You may also be interested in...

Comments and Discussions

 
QuestionMy vote of 5 Pin
PPS Gusain13-May-13 8:52
memberPPS Gusain13-May-13 8:52 
AnswerRe: My vote of 5 Pin
Faisal(mfrony)13-May-13 21:11
memberFaisal(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
memberPPS Gusain11-May-13 5:35 
AnswerRe: Code does not work - It works mostly my Vote of 4 Pin
Faisal(mfrony)12-May-13 21:46
memberFaisal(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
memberPPS Gusain13-May-13 8:27 
Questioncode does not work Pin
PPS Gusain9-May-13 3:27
memberPPS Gusain9-May-13 3:27 

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

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

| Advertise | Privacy | Terms of Use | Mobile
Web03 | 2.8.150603.1 | Last Updated 2 May 2013
Article Copyright 2013 by Faisal(mfrony)
Everything else Copyright © CodeProject, 1999-2015
Layout: fixed | fluid