CSC/ECE 517 Fall 2011/ch1 1c ka: Difference between revisions
No edit summary |
|||
Line 70: | Line 70: | ||
In this case, the function asyncAPI() immediately returns after making the httpAsyncCall to the server. Later, when httpAsyncCall() finishes, it will invoke the callback() function passed to it. | In this case, the function asyncAPI() immediately returns after making the httpAsyncCall to the server. Later, when httpAsyncCall() finishes, it will invoke the callback() function passed to it. | ||
But because of closures, the callback will continue to have access to the values of uniqueId and user_cb, even after asyncAPI returns. Hence it can invoke the appropriate user_cb() function once it gets the result. ??What happens when it is called back to back? | But because of closures, the callback will continue to have access to the values of uniqueId and user_cb, even after asyncAPI returns. Hence it can invoke the appropriate user_cb() function once it gets the result. ??What happens when it is called back to back? | ||
*Closures can be used to implement Factory design pattern. | |||
E.g | |||
<pre> | |||
function showHelp(help) { | |||
alert('showHelp'+help); | |||
} | |||
function makeHelpCallback(help) { //Factory function | |||
//Make some initializations | |||
return function() { | |||
showHelp(help); | |||
}; | |||
} | |||
var rubyHelp = makeHelpCallback("Ruby"); | |||
var jsHelp = makeHelpCallback("JavaScript"); | |||
//These handles can be passed to anybody and later invoked like: | |||
rubyHelp(); //Will pop up "help" specific to Ruby | |||
jsHelp(); //Will pop up "help" for JavaScript | |||
</pre> | |||
*Closures can be used for pre-processing complex computations ?? | |||
<pre> | |||
Dictionary = (function () { | |||
//does sorting of the entire word list | |||
sortWordList(); | |||
return { | |||
search : function (word) { | |||
//Searches for the given "word" in the sorted list of words | |||
} | |||
} | |||
})(); | |||
</pre> | |||
Here the function sortWordList() and the surrounding code (except the return statement) is executed the moment this JavaScript file is included (or parsed). Since sorting the entire word list could be a time consuming operation, this takes place before any request for searching arrives. Once this is done, anytime a call to search() can be executed efficiently on the already sorted list available to it. | |||
</pre> |
Revision as of 04:48, 6 September 2011
Wiki Chapter: CSC/ECE 517 Fall 2011/ch1 1c ka
Introduction
This article discusses the advantages of using closures over methods. There is a common argument over the necessity of closures and the way in which the closure behavior can be achieved by using anonymous classes. On the contrary, closures have more to their credit than what is the general perception that they increase the complexity and disrupt simplcity of the syntactic sugar provided by the programming languages. We try to identify some of the benefits of closures in this article.
Closures
The concept of closures has been around for a long time. Closures were first implemented fully as a language feature in 1960 in the programming language Scheme. They were used to implement the lexically scoped first-class functions (that is functions that are treated as first-class objects. A closure is the function value which is treated as an object and which contains references to the variable names in the lexical environment which was active when the closure was evaluated. In simple terms closures can be thought of as blocks of code which can be passed around as objects and which have access to the context in which they were first declared. This allows you to separate out the control structures, logical operators, loop operators etc. from the details of how they will be used. Closures will help you save the context of a function after it is executed, that is after some initialization is done. This context can be used at a later point in time.
Practical significance of Closures
- In Object oriented languages, classes are used to represent real world objects. This is possible because, classes have their private members,private and public functions,etc which enable object orientation. Closures can support similar functionality with much more ease, without having to create Classes,Objects,etc. Hence Closures form one of the most handy yet powerful tools of dynamic languages.
For Example,
myobj = (function () { var privatefunction = function () { alert('hello'); } var privateVariable = "Private" return { publicfunction : function () { privatefunction(); } } })();
The myobj closure contains a private function and a private variable which cannot be accessed by anybody outside myobj. It also provides an external interface using the function publicfunction(). You can simply access the method publicfunction() without actually instantiating any class or object.
- Closures can be used to implement interfaces. When developing API libraries, we will have to often provide an interface definition and a set of functions that can be called upon it. Closures are perfectly suitable for this kind of implementation.
E.g Suppose you are writing a JavaScript library for providing a set of Calendar APIs. The interface could be defined this way:
Calendar = (function () { var calendarName = "file.db" //Unique Identifier for this Calendar Object return { addCalendarEntry : function (entry) { //Operates on Calendar file.db (as specified by calendarName param) } } })();
A user of this API library could use it as:
Calendar.addCalendarEntry(calendarEntry);
without worrying about its initializtions, instantiation,etc.
- Closures can be best used for Event handling in case of Asynchronous calls. This is especially true about AJAX and Web Service calls.
E.g.
function asyncAPI(uniqueId, user_cb) { function callback(result) // This will be invoked with "result" once httpAsyncCall() completes { user_cb(result,uniqueId) } jsObj.httpAsyncCall(callback) //Actual Client-server call }
In this case, the function asyncAPI() immediately returns after making the httpAsyncCall to the server. Later, when httpAsyncCall() finishes, it will invoke the callback() function passed to it. But because of closures, the callback will continue to have access to the values of uniqueId and user_cb, even after asyncAPI returns. Hence it can invoke the appropriate user_cb() function once it gets the result. ??What happens when it is called back to back?
- Closures can be used to implement Factory design pattern.
E.g
function showHelp(help) { alert('showHelp'+help); } function makeHelpCallback(help) { //Factory function //Make some initializations return function() { showHelp(help); }; } var rubyHelp = makeHelpCallback("Ruby"); var jsHelp = makeHelpCallback("JavaScript"); //These handles can be passed to anybody and later invoked like: rubyHelp(); //Will pop up "help" specific to Ruby jsHelp(); //Will pop up "help" for JavaScript
- Closures can be used for pre-processing complex computations ??
Dictionary = (function () { //does sorting of the entire word list sortWordList(); return { search : function (word) { //Searches for the given "word" in the sorted list of words } } })();
Here the function sortWordList() and the surrounding code (except the return statement) is executed the moment this JavaScript file is included (or parsed). Since sorting the entire word list could be a time consuming operation, this takes place before any request for searching arrives. Once this is done, anytime a call to search() can be executed efficiently on the already sorted list available to it.