Tag Archives: closure

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