Javascript Closures

I’ve been working on a web application project for about a year now.Seven months ago i switched to object-oriented javascript due to complexity of the project.It increased productivity in a way that i can not express with words , you just have to experience it.

As i switched to object oriented javascript i learned some new tricks in javascript that i’ve never needed or used before.One of them was closures.I dont think i’m yet an expert on javascript or its closures but i want to share my experiences with it. I perceive closures as parameterized callback functions that you can pass arguments into the function.

So when it becomes useful you ask?
It becomes very useful when you are using Jquery & OOP javascript together. Let me give you an example:

  • Content 1
  • Content 2
  • Content 3

This will not work as expected because second “this” pointer becomes current $(‘li’) element.
So how you gonna handle it?
You can fix it by editing it to:

$(this).html(obj.counter);

But wait that’s against OOP approach to assume object name is always going to be “obj”.I wish it was just that , but it will also make it impossible to declare and use more than one instance of that class in one document which can be solved by using seperate documents and showing them in one page within iframe elements.But dont you think it is quite unprofessional?

So that’s where we use Javascript Closures.By using a closure we can pass object pointer keyword “this” into “each()” function of JQuery.
for working example click : http://jsfiddle.net/C7yen/

  • Content 1
  • Content 2
  • Content 3

PS:
Some of the JQuery functions such as “.bind()” allows you to pass arguments.In those cases you dont need closures.But those functions are very few , maybe its only “.bind()” function , because it’s only one i know.

    ;
  • Content 1
  • Content 2
  • Content 3

4 thoughts on “Javascript Closures

  1. Volkan Özçelik

    Hi Ahmet,

    JavaScript is a prototypal language in an of itself.

    Many gurus (including Douglas Crockford himself) have admitted that it had been a philosophical mistake having been used JavaScript in an object oriented fashion.
    — it’s against its nature.

    Coming to your example. Each function in JavaScript is “by definition” a closure that closes over the global window object. Since you define a static global namespace “obj”; it is perfectly and utterly legitimate to refer to this namespace within your code base.

    Optimization without measurement is not an optimization; and the depth of execution scope is hardly ever a problem in your example, but it’s worth to mention that defining a closure within another closure, or dynamically binding context using .bind, and using this within a loop increase the depth of execution scope. This may result in a slower running JavaScript code.

    So instead of making things overly-convoluted, the below may saner a better approach — your mileage may vary of course.

    var obj = {
    counter:1,

    set: function() {
    var self = window.obj;

    //besides using a good old for loop instead of $.each will be a lot faster.
    $(‘li’).each(function(){
    $(this).html(self.counter);
    });
    }
    };

    The above code is not against any object-oriented programming practices.

    These three links may be some pointers to the right direction:

    “Everything You Need To Know About JavaScript Functions (and more)”
    http://o2js.com/2011/11/05/functional-programming-in-javascript/

    “Functions and Closures in JavaScript”
    http://o2js.com/2011/04/26/functions-and-closures-in-javascript/

    “The JavaScript Module Pattern”
    http://o2js.com/2011/04/24/the-module-pattern/

    hope that helps,
    Volkan

    Reply
  2. admin Post author

    @Volkan Özçelik
    Actually i used “obj” namespace and javascript’s own object oriented approach above just to demonstrate the use of closures.
    In my actual project , i use Classy.JS library which is very similar to OOP approach of Python , actually inspired by python.
    In Classy.JS
    You define classes as :
    var NewClass = Class.$extend({
    __init__:function()
    {

    }
    });
    and declare object as follows:
    var Object = new NewClass();

    so you cant use NewClass or Object namespace in Classy.JS , if you use – and i did use in the past before i knew closures – that makes it impossible to declare more than one instance of same class in one document. :)

    Reply

Leave a Reply to Ben Aluan Cancel reply