Showing posts with label Javascript. Show all posts
Showing posts with label Javascript. Show all posts

Saturday, May 31, 2014

JavaScript Performance tip using a Closure

Here is a simple performance JavaScript tip using a JavaScript closure that is so quick to explain you have no reason not to keep reading.   Consider this: you want a function which will tell you the position on a rugby team for a certain number. Those of us who are familiar with the sport will know that in rugby, the various positions always have the same number.
  1. Loose head
  2. Hooker
  3. Tight head
  4. Lock
  5. Lock
  6. Flanker (blind side)
  7. Flanker (open side)
  8. No. 8
  9. Scrum half
  10. Out half
  11. Left wing
  12. Inside Centre
  13. Centre
  14. Right wing
  15. Full back
So for your first attempt you define a positions array in the global namespace and then a function to resolve the position for a given number.
var positions = ['No position', 'Loose head', 'Hooker', 'Tight head', 'Lock', 'Lock', 'Flanker', 'Flanker', 'No. 8',  'Scrum half', 'Out half', 'Left wing', 'Inside centre', 'Outside centre', 'Full back']

var getPosition = function(n) {
   return positions(n);
}
Everyone starts laughing at you at code review time. You get comments such as:
"Don't pollute the name space, re-write please."
"Did you even bother using JsLint?"
"Do you want fries with that?"

For your second attempt, you put the positions array into a function as a local variable.
var getPosition = function() {
    var positions = ['No position', 'Loose head', 'Hooker', 'Tight head', 'Lock', 'Lock', 'Flanker', 'No. 8', 'Flanker', 'Scrum half', 'Out half', 'Left wing', 'Inside centre', 'Outside centre', 'Right wing' 'Full back'];   // positions is a local variable
   return positions[n];
}
Back at the second code review:
"Well it's better, but you do realise that every time that function is called, the array is allocated?"
"But you said, don't pollute the global name space"
"Look we have standards here, don't pollute global name space and don't incur performance costs when you don't need do"
"Ok"

You leave the code review despondent and crestfallen. Back at your coffee stained desk, when your headphones are on low volume, you keep hearing the word closure, closure, closure from a few of the JavaScript nerds sitting near you.  That evening, you are having difficult getting to sleep.  Closure, closure, closure.  The word won't leave your head.  Closure, closure, closure.   Yeah you know that closures offer a way to encapsulate code in JavaScript, but this isn't about encapsulation. Wait a sec! Closures close over free variables and make them accessible to the lexical scope. Hmmm... This means you could do something like...
var getPosition = function () {
    var positions = ['No position', 'Loose head', 'Hooker', 'Tight head', 'Lock', 'Lock', 'Flanker', 'Flanker', 'No. 8', 'Scrum half', 'Out half', 'Left wing', 'Inside centre', 'Outside centre', 'Right wing', 'Full back'];   // positions is a local variable
    return function(n) {
        return positions[n];
    }
}()

console.log(getPosition(4));
What's going on here?
  • The inner function "closes over" the positions array
  • The outer function returns the inner function, which is then assigned it to the variable getPosition
  • The outer function is self invoking. This means the declaration, invocation and assignment will happen all at the same time.
  • Because it is the outer function which allocated the array and because the outer function is only invoked once, the array is only allocated once.
  • Because the inner function has access to what it "closes over" even after the outer function has executed, it means the inner function will have access to the positionsarray (that is only allocated once).
So you return to code review a little more sanguine. You get one comment:
"Third time lucky"

You might be thinking, it doesn't take that long to allocate an array in JavaScript is this not overkill? Well, it depends. Is your application needing to squeeze every nano second? Is the amount of data you need to initialise a lot more than 15 elements in an array? These are pertinent questions of course. But the technique is a handy one to know because encapsulation is clearly not the only advantage of closures.

Monday, June 17, 2013

JavaScript tip: Log those important APIs and get some code coverage

Any web architecture using JavaScript will always have plenty of AJAX requests to the server. There are many, many, many different ways AJAX calls can be made. Suppose you're thinking good software engineering and you want to avoid coupling your client code to the AJAX mechanism you are using? You could use a wrapper / bridge / proxy type object which contains all the APIs to get information from the Server and encapsulates your AJAX mechanism. Following the Crockford Module pattern this could pan out something like:
dublintech.myproject.apiBridge = function() {
    function createEntity(data) {
        ...
        // actual AJAX call
        ...
    }
 
    function readEntity(id) {
        ...
        // actual AJAX call
        ...
    }
 
    that = {}
    ...
    that.createEntity = createEntity;
    that.readEntity = readEntity;
    return that;
};
This could be invoked simply as:
apiBridge.createEntity(data);
What are the pro's of using the wrapper approach? Well essentially the advantages are all derived from the fact there is a nice separation of concerns: the transport mechanism (doesn't even have to be ajax) is separated from the actual data requests coming from the client. This means:
  1. If you wish to change Ajax mechanism (i.e. move from one Ajax library to another), it's not a big deal. The impact is limited.
  2. It's easier to stub out and test.
  3. It's easier to achieve code reuse. Suppose you want to have consistent error handling for exceptions from Ajax requests, it's much easier to do this if all Ajax request are following the same pattern.

Tell me something more interesting.

Well we all know that you can see the AJAX requests in firebug. But say you wanted another way to log what requests had been invoked on your wrapper. In Java, you could write an Aspect and set it on every method that made an Ajax request. There is no direct equivalent to aspects in JavaScripts. But we can do something similar. Firstly, the function to do the pre and post logging:
function wrapPrePostLogic(fn) {
    return function withLogic() {
 console.log("before" + fn.name);
 var res = fn.apply(this, arguments);
 console.log("after" + fn.name);
    }
}
Ok so wrapPrePostLogic takes a function, and returns a new function which wraps around the existing function and puts logging before and after the invocation of that function. Hold on sec - IE is awkward. It doesn't support getting the function.name variable. So let's write a helper method to get function name for any browse and use that instead.
function wrapPrePostLogic(fn) {
    return function withLogic() {
        getFnName("before " + getFnName(fn));
        var res = fn.apply(this, arguments);
        getFnName("after " + getFnName(fn));
    }
}

function getFnName(fn) {
    var toReturn =  (fn.name ? fn.name : (fn.toString().match(/function (.+?)\(/)||[,''])[1]);
    return toReturn;
}
So now what we need to ensure wrapPrePostLogic() is called for every method. We could do:
    that = {}
    ...
    that.createEntity = wrapPrePostLogic(createEntity);
    that.readEntity = wrapPrePostLogic(readEntity);
    ...
    return that;
But I am smelling code bloat and human error. What would be nicer is to iterate over all functions returned by that and wrap them appropriately. To do that we could do...
    that = {}
    ...
    for (var prop in that) {
        if (typeof that[prop] === "function") {
            that[prop] = wrapPrePostLogic(that[prop]);
        }
    }

    return that;

Not bad. Anything else?

Ok, so say you are you using a UI test framework and wanted to test code coverage of all methods that send / receive data to / from the server. Instead of getting your wrapper function to log to the console you could update a hidden div and then make your test framework check this hidden div.
function updateHiddenDiv(methodName) {
    if (jQuery("#js_methods_invoked").length === 0) {
        var hiddenDiv = jQuery('
Now we can just change our wrapper function to:
function wrapPrePostLogic(fn) {
    return function withLogic() {
        var res = fn.apply(this, arguments);
        updateHiddenDiv(fn.name);
        return res;
    };
}
In addition, you can find what JavaScript methods have been invoked by opening a JavaScript console and wacking in:
jQuery(#hiddenDiv).
This will return what methods have been invoked. Until the next time, take care of yourselves!

Thursday, December 27, 2012

A JavaScript Quiz and a JavaScript Quiz Engine

Here is a very simple JavaScript quiz for you to try and have some fun with!
For this quiz, I wrote a very simple quiz engine using JavaScript and some JQuery APIs. To create a quiz all you need to do is create a JSON object which contains Question / Answer info and pass it to a single API. The engine will:
  • determine if a question has a single answer or multiple answer and show radio buttons or check boxes accordingly.
  • display user progress
  • display results and correct / incorrect questions.
Source code is on my GitHub. I have also put the files on github pages. So if you want a quiz on your site, import the engine by simply importing the CSS and the JavaScript (ensure you also have JQuery being pulled in from somewhere).


Then create a JSON object of your questions and answers. The JSON object is an array of Question / Answer. Each element in the array consist is a map of three elements:
  • The question
  • The possible answers (the answers to present to the user) - specified as an ordered array.
  • The correct answer
For example:
var quiz_questions = {questions:[
                             {"question":"Which of the following is a risk of using Constructor function?", 
        "answers":["If it is invoked without using new keyword, the this variable is not bound to local object but to the global namespace.", "Performance risk", "There are no risks"],
        "correct_answer":"0"}, 
        ...]
The correct answer is a numeric value, which represents the position in the list of the possible answers. If there is more than one correct answer, separate the correct answers by commas. For example:
{"question":"Which of the following is true about functions?",
        "answers":["Functions can be expressed as literals", 
                   "Functions can be assigned to variables, array entries and properties of other objects",
             "Passed as arguments to other functions",
             "Returned as values from functions",
             "Can have properties created and assigned dynamically",
                                           "Can solve climate change?"],
         "correct_answer":"0,1,2,3,4"}
The engine will use check boxes for questions that have multiple answers and radio boxes for questions that have a single answer. To invoke the engine, it is just one API.
quizModule(quiz_questions, $('#intro'));
In this case $('#intro') is the dom element I want the quiz to sit below. quiz_questions is the JSON object containing the question / answer pairings.

There is no server request handling whatsoever after the quiz loads. Everything happens client side from the first question to the generation of results.

If you have any interesting JavaScript questions send them on and I'll add them to the quiz! Or use the engine and create your own quiz.

Wednesday, November 14, 2012

Unit Testing your JavaScript

According to John Resig and Bear Bibeault 48% of JavaScript developement (see chapter 2, Secrets of the Java Script Ninja) do not test.  The advantages of unit testing code and developing in a test driven approach have been well documented and don't need to be rehashed - suffice to say the arguments are equally applicable to JavaScript code.  One popular approach to unit testing JavaScript is the QUnit framework. This framework was originally built to test JQuery and then evolved into a stand alone unit testing option for JavaScript in its own right. Let's consider an example. Suppose we have an architecture where the Web Tier makes AJAX REST style requests to a server and gets back information about entities in JSON format. It is probable that we will want to adapt the data that comes back into custom JavaScript objects that we can send on to various parts of the GUI. To convert the data, we use something similar to the GOF Adapter pattern. We collate methods involved in adapting different entities and then place them all in an object literal as follows:
var dublintech = dublintech || {};

// dataAdapter contains some functions to convert data.
// Idea is this can map JSON results from REST requests 
// to JavaScript formats the GUI expects.
dublintech.dataAdapter = {
    adaptStudents : function (data) {
        var adaptedStudentsVar = {
            students:[]
        };
  
        jQuery.each(data.students, function(indx, originalStudent){
            var student = {
                name: originalStudent.firstName + " " + originalStudent.lastName,
                dateOfBirth: originalStudent.dateOfBirth,
                nationality: originalStudent.nationality
            };
            adaptedStudentsVar.students.push(student);
        });
        return adaptedStudentsVar;
    },
 
    adaptHumans : function (data) {
       // ...
       // code to adapt humans
    },
 
    adaptAnimals : function(data) {
       // ...
       // code to adapt animals.
    }
};
This approach achieves a separation of concerns and is a good attempt at making things follow a stateless and functional paradigm.  
Note 1: Yes the above example is super simple. The only adaptation that is really happening is that the adpated name variable is made up from combining the first name with the last name that are in the JSON. The real world is obviously a more complicated place, but this simple adaptation example is enough to show how things hang together using QUnit.
Note 2: If you are wondering why I did not use a closure above, it is because there is no need for any state in these methods, hence there is no need to encapsulate any state. But again, in the real world you may not find it so easy to avoid state and if it comes you are better off encapsulating it using a closure.

And now the tests...

Ideally you'd like if:
  • any required testing libaries were taken from a public CDN.
  • your tests are 100% separate from your JavaScript code and have no impact your original source code.
  • your tests are easy to run and even easier to get results from.
To use the QUnit approach we simply write some JavaScript using the QUnit APIs in a HTML page. See below:
<html>
<head>
  QUnit basic example
  
  
  
  
</head>
<body>
  
<!-- test code </body> </html>

Now the salients points:
  1. The test exists in a separate file. It creates some test data, passes it to the adaptStudents method and checks that what is returned is what it should be.
  2. The JavaScript which contains the code that is being tested can be located anywhere that can be accessed by a HTTP request. So your test code does not have be located on the same machine / building as the JavaScript it is testing.
  3. The QUnit, JQuery libraries are pulled in from a CDN. 
  4. The test() API is a QUnit API which does exactly what it says  - that there is a test to execute!  There can be multiple tests() in the same file and they can be grouped using the module() API.
  5. equal() is a QUnit API which performs the actual test. QUnit has other assertion APIs (ok() and deepEqual()).
  6. It's simple to run this test. Just access this page in a web browser.
When the test is run, you get a picture like this:
Results
The results contain the following checkboxes
  • Hide passed tests - useful when you want to focus only on tests that failed
  • Check for globals - when selected QUnit will make a list of all properties on the window object, before and after each test and will check for differences. If properties are added or removed, the test will fail. 
  • No try/catch - If your test throws an exception, the testrunner will die, unable to continue running and will you will get the a  "native" exception. This can help debugging old browsers with bad debugging support like Internet Explorer 6.
The results page also contain the user agent used to run the tests (useful for screen shots), the total number of tests ran, the success summary and the overall execution time.  Each test is then detailed - including the number of failures, the numbers of success and the number of asserts in the test i.e. in this case (0, 3, 3).  You can also specify the number of assertions in a test and if they are not all invoked, the test will fail.

Anything else? 

Yes, QUnit can be used to test Asychronous code.  There are special APIs to indicate asynchronous code is being tested. QUnit can also test user interaction by leveraging JQuery trigger APIs.

What about mock objects?

There is no support for mock objects out of the box. However, there are a number of frameworks such as mockjax and sinjo.js  (in fact sinon.js has special support for QUnit).
Finally, I have put the source code detailed above on my Github.

Sunday, September 23, 2012

Is Java Dead or Invincible?


Is Java Dead?

Writer Isaac Asimov once said that "the only constant is change".  That isn't just a phrase in the software industry, it is an absolute fact.  Once, there was a day when Corba was king but it was usurped by Web Services.  Even within the world of Web Services, that used to be all about SOAP but now it's REST style services which are much more popular today.  Now somethings will obviously hang around a bit longer than others.  Relational databases have been around 40 years and aren't going to be kicked out by NoSql just yet. The HTTP protocol has been at version 1.1 since 1999 and has helped us use a thing called the Internet.  As for Java well that has been a pretty popular computer programming language for the last decade and a half.

According to Dutch research firm Tiobe in terms of overall popularity, Java ranked 5th in 1997, 1st in 2007 and 2nd in Sept 2012. At the time of writing there are over 2,000 Java progamming books on Amazon in English and there are almost 300,000 threads on Stackoverflow related to Java.   However, as George Orwell once said: "Whoever is winning at the moment will always seem to be invincible". But is Java invincible or beginning to die?  That's the question being asked more and more now.

In my humble opinion, the challenges to Java can be split into three categories:
  1. The rise of alternative languages
  2. Scalability / Multi-Core processors
  3. The return of the fat client.
Let's elaborate...

The rise of alternative languages

Alternative languages can be split into two groups: those that run on the JVM (Scala, Groovy etc)
and those that don't (Python, Ruby).  One interesting thing is that the first group is pretty large.  The languages that run on the JVM aren't mutual exclusive to Java and in a sense strengthen it reminding us what a remarkable piese of software engineering the JVM is.  Development teams can get that
extra bit of expressiveness in a niche language like Groovy, but can still call out to Java when they need some cool Java library or just need that extra bit of performance.  Remember the advantages in Groovy 2.0 speed it up but it is still not as fast as Java.

As for the features some of these languages provide that are not in Java, well that is the case but it won't always be the case.  Take a look at the roadmap for Java 8 and the features it will include. Just like Java EE 5 and 6 took ideas from Spring / Seam,  the Java lanuage in its 8th major release will be taking ideas from other languages. For example literal functions will be facilitated by Lambdas.  Java 8 Lamdas will have support for type inference and because they are just literals it will be possible to pass them around (and return them) just like a String literal or any anonymous Object.

That means instead of having to write an implementation of Comparator to pass to the Collections sort utility to sort a list of Strings, in Java 8 we will just do:
Collections.sort(list, (s1, s2) -> s1.length() - s2.length());

So, the alternative JVM languages don't exactly kick Java out of the party. It is still there, but in a party that has a better selection of music played and in a party where the guests encourages their host to be a better host.

Scaling on the multi-core platforms

As for multi-core and JVM - we all know that with a JVM running on a single core it was possible to spawn threads in the very first release of Java.  But these threads weren't executing in parallel, the CPU switched between them very quickly to create the impression that they were running in parallel. JStack may tell you that 50 threads have state "runnable" on your single core machine but this just means they are either running or eligible to run.  With multi-core CPUs it is possible to get true parallelism.  The JVM decides when to execute threads in parallel.

So what's the deal here?  Firstly, even though concurrency and threads were a feature of Java from the very beginning the language support was limited meaning development teams were writing a lot of their own thread management code - which could get ugly very quickly. This was alleviated greatly in JDK 1.5 with the arrival of a range of thread management features in the java.util.concurrent package.  Secondly, to get better parallelism something else was needed.  This came in Java 7 with Doug Lea's Fork / Join framework which uses clever techniques such as work stealing and double sided queues to increase parallelism. However, even with this Framework decomposing (and re-arranging) data is still a task that is needed to be done by the programmer.

Functional progamming gives us another option to perform computations on data sets in parallel.  
In Scala, for example, you just pass the function you wish to operate on the data and tell scala you want the computation to be parallelised.
outputAnswer((1 to 5).par.foreach(i => longComputation))

And guess what? The same will be available in Java 8.
Array.asList(1,2,3,4,5).parallel().foreach(int i ->heavyComputation())
Since scalability and performance are architectural cousins, it is worth stating that in many experiements Java still out performns other languages.  The excellent Computer Language Benchmark Game shows Java outperformaning many languages. It hammers the likes Perl, PHP, Python3, Erlang in many tests, beats Clojure, C# in nearly all tests and is only just behind C++ in terms in the performance results. Now,  performance tests can't cover everything and a context will always have some bias which favours one language over another but going by these tests it is not as if Java is a slow coach.

The fat client is back!

The return of the fat client

Since the advent of AJAX, Doug Crockford telling people how to use JavaScript and the rise of an excellent selection of JavaScript libraries the fat client is truely back.  Close your eyes and imagine what a cool single page web application such as gmail would look and feel like if it was just thin client web framework based on Spring MVC, JSF or Struts - you just cannot beat the performance of a well designed fat client.

One saving grace is that JavaScript is a lot more difficult to be good than some people think. It takes a lot more thinking to really understand  Closures, Modules and the various JavaScript best practises than it does to know your way around a web framework like Spring MVC and Struts. In addition, building a single page web application (again such as gmail) doesn't just require excellent JavaScript understanding it requires understanding of how the web works. For example, browsers don't put Ajax requests in the browser history.  So you gotta do something smart with fragment identifiers if you want the back and forward buttons to be usable and meaningful for the User.

There is a probably some room here for a hybrid approach which uses both a web framework and JavaScript and of course some JavaScript libraries.   This gives developers a structure to build an application and then the opportunity to use JavaScript, JQuery or whatever cool library takes there fancy for important parts of the Application that need to be jazzed up.   In a true fat web client approach, there should be no HTML served from the server (that means no JSPs), the only thing coming back from the server is data (in the form of JSON). However,  using a hybrid approach you can make a transition from thin to fat easier  and you can still put your JavaScript libraries on a CDN, you just won't get all the advantages of a full fat web client approach.

Summary

In summary, Java has had some bad moments. AWT was a rush job, Swing had performance problems, the early iterations of  EJB were cumbersome and JSF was problematic in comparison to other frameworks such as Struts and Spring MVC.  But, even today, extremely innovative projects such as Hadoop are built using Java.  It still has massive support from the open source community. This support has not only helped Java but also show Java some its problems and things it needs to get better at.   Java has shown it has the ability to evolve further and while other languages challenge it I don't think the game is over just yet.  It goes without saying, a lot will of the future of Java will depend on Oracle but let's hope whatever happens that the winner will be technology.

References

  1. Yammer and their migration to scala
  2. James Gosling taking about the state and future of Java at Google tech talk
  3. Article from Oracle describingFork and Join in Java 7
  4. Eric Bruno:Building Java Multi-Core applications
  5. Edgardo Hernandez:Parallel processing in Java
  6. IEEE top ten programming languages
  7. JDK 8 downloads
  8. Java Code Geeks article on Fork Join
  9. Good Fork Join article by Edward Harned
  10. Fork / Join paper from Doug Lea
  11. Fork / Join Java updates information from Doug Lea
  12. Scala Java Myths - great article by Urs Peter and Sander van der Berg

Monday, August 6, 2012

Make that form for User friendly!

I am reading the jQuery Cookbook at the moment. I will blog some interesting examples that I am come across and pad them out - if even only slightly - in the hope that they make more sense to the untrained eye. Let's begin! Consider a form as such:

Who is going to win the Heineken cup next year?

Click on any one of the teams, notice that the radio box is selected. Then start typing in the "Other" text box. Isn't it a bit odd that the team you previously selected is still selected even though you clearly started typing in the "Other" textbox? Does the user seriously have to explictly select the "other" radio button even though an "other" indication has already been given? Now, try this. Clear out the "other" text box and select another team. Then select the "other" radio button. Notice that the "other" textbox does not have focus even though you are hardly going to click the "other" check box and not want to type anything into the corresponding text field. Good GUI should assume the user will want to behave rationally. When the "Other" radio box is selected, it makes sense that its adjacent text box should get focus. Remember good usability means the user can achieve what they want with less clicking. And remember, good usability means that things are intuitive and GUIs do not display contradictions. So with all that in mind, we can include the discussed usability guidelines and come up with something like this:

Who is going to win the Heineken cup next year?

So how did we do that? Well let's take a look at code:

Discussion:

  1. :text is a JQuery psuedo class Selector which selects all elements of type text. As per JQuery recommendations, pseudo class Selectors should be preceded with another selector or tag element otherwise the universal selector is implied. In this case we do input:text and only one text box will be selected. That's ok.
  2. The .each(function(){ means iterate overall inputs of type text and execute the specified function. Don't forget ".each" can operate on sets of elements of any size including just 1 which is the case in this example.
  3. $(this) corresponds to the object which is being operated on by each. In this case it is each input text box. If you don't believe me add:

    
      console.log("this is: " + $(this)[0].id);
    
    

    and you will see something like:

    this is: Source5Txt in the console.

  4. The inputText button and radio button are stored in the local context. This is for efficiency.
Til the next time take care of yourselves.

Sunday, August 5, 2012

How JQuery changed events...

Event handling helps to enrich any application and that most definitely includes web applications. Do this when the button is clicked! Do this when the page has finished loading! Client side JavaScript has a range of event handling options. Before the days of funky JavaScript libraries such as JQuery, when the web was in its embryonic stage, event handling was achieved purely in JavaScript. One technique was to set the event handling properties to some JavaScript code. For example:
...


Here the onclick event property is set so that the an alert message is shown when the button is clicked. The Window object, Document node and the various Element objects all have a selection of event properties. Some of the more interesting ones are:
  • window.unload - triggered when user is navigating away from from a document.
  • form.onchange - can be used to capture a change from any element in the form thru a technique known as bubbling.
  • element.onload - every document element (e.g. ,
All seemed much nicer, but IE complicated things:
  1. IE8 did not support addEventListener(). Instead you had to use attachEvent()
  2. Event handlers usually receive an Event object (http://www.w3schools.com/jsref/dom_obj_event.asp) which contains details of the event. This will contain properties such as the element that trigged the event, the name of the event and the time it was created etc. To receive this event simply add it to the event handler.
    button.addEventListener("click", function(event) {
        alert("You clicked me with an event of type!" + event.type)}, false);
    
    But you guessed it, IE8 did not support this mechanism to get details of the event and instead, you had to check the global variable window.event to get information about it. This lead to messy JavaScript code such as
    function handler(event) {
        event = event || window.event;  // got to cater for Microsoft!
    }
    
  3. The "this" keyword in the event handling code usually referred to the document element that fired the event. However in IE8's attachEvent(), the this referred to the global window.
JQuery comes to the rescue providing APIs that work in all browsers. The commonly used events (e.g click, load) have their own event registration APIs (click(), load()). Similar to JavaScript's addEventListener() the JQuery event handler APIs allow multiple event handling logic to be associated with the same event. And similar to JavaScript, JQuery event handler functions do not have to have arguments or return values but both are supported. The value add being that JQuery APIs work and all browsers - that means event objects are passed into event handlers for poor old IE8!
//add to all button elements
$("button").click(function() {alert("You clicked me");}); .
So JQuery clearly solves some problems here. Does it offer anything else? Of course... the bind() API. This allows:
  • the same handler to be executed for multiple events. Just separate the events by a space.
    // invoke myEventHanlder for any click, mousedown events for any div elements.
    $('div').bind('click mousedown', myEventHandler);  
    
  • the same handler function to be reused with different data. This is achieved by passing an Object literal as the second object in the bind API. The object literal values can then be read in the event handler via the event objects data properties.
    // call buttonClicked and pass color red to it.
    jQuery('#button1').bind('click', {team:'Leinster'}, buttonClicked);
    // call the same buttonClicked function but pass blue. 
    jQuery('#button2').bind('click', {team:'Munster'}, buttonClicked); 
    
    buttonClicked function could then be something like:
    function buttonClicked(event) {
        alert("you selected team" + event.data.team);
    }
    
  • Refer to multipe event handlers at the same time. This is achieved in JQuery by using namespaces for the events. Suppose you want to group a selection of events. You could put them all into the same namespace click.myclickevents.
    $("#myButton1").bind('click.myclickevents', myfunction());
    $("#myButton1").bind('mousedown.myclickevents', myfunction());
    
  • Because they are grouped they can be reffered to now at the same time. This comes in handy if you want to remove them.
    $("#myButton1").unbind('myclickevents');
    
In addition JQuery provides:
  • The one() API. This is similar to bind, except the eventhandlers only get called once. They are then deregistered.
  • The trigger() API. This provides the ability to manually cause event handlers (including custom events) to be invoked.
  • Live events This is like the event handling achieved with the bind() except it will also add event handling logic to new elements that are to still to be created, whereas bind() only adds it to existing elements.
The End?

Not quite. In order to stop people getting confused about the various JQuery event handling APIs JQuery unified them all into one API, the on() API. See also 1.7 release notes.

Tuesday, July 24, 2012

Are you leaving my site?

A website will always contain some links. Links fall into one of two categories:
  1. Internal links - links to other parts of your website.
  2. External links - links to other websites external to your website.

There are times when it might make sense to warn the user you are leaving your site. For example, you may have a SAAS style architecture with external links. It is good usability to differentiate links that keep the user on the site and links which will take the user away from the site especially if the latter could invalidate a transaction or session. Even if nothing could become invalidated it must just to differentiate in cases when the site the user will be trvalleing to next is very similar (which might lead the user to think it is the same site), or it might just be nice to say bye.

Well one way you could do this is to use some JQuery to select to all external links and add some JavaScript to execute to warn the user of the results of their action.

Check it out...



Try it out... An explanation of the code:
  • a[href^='http:'
    The ^ after href means means all elements that begin exactly with http:. This is an example of how JQuery builds on CSS selectors.
  • :not([href*='"+location.hostname+"'])
    means match elements that do not match the window.location.host property. Don't forget jquery provides many powerful selection filter expressions using the (:) syntax, Other examples are :first, :odd and :even.
  • ... location.hostname
    is the dom way of figuring out the hostname of your site.
  • attr("target","_blank")
    is a browser standard to open a new window.
  • .click
    is the JQuery method whichs binds custom event handler to the the JavaScript "click" event.

Sunday, April 1, 2012

JavaScript language a- z cheat sheet

Here is an A - Z list of some Javascript idioms and patterns. The idea is to convey in simple terms some features of the actual Javascript language (rather than how it can interact with DOM). Enjoy...

Array Literals
An array literal can be defined using a comma separated list in square brackets.
var months = ['jan', 'feb', 'mar', 'apr', 'may', 'jun', 
                     'jul', 'aug', 'sep', 'oct', 'nov', 'dec'];
console.log(months[0]); // outputs jan
console.log(months.length) // outputs 12

Arrays in javascript have a wide selection methods including push() and pop().  Suppose the world got taken over by a dictator who wanted to get rid of the last month of the year? The dictator would just do...
months.pop();
And of course, the dictator will eventually want to add a month after himself when everyone will have to worship him:
months.push("me");

Callbacks
Since functions are objects, they can be passed as arguments to other functions.
function peakOil(callback) {
    //... code
    callback();  // the parentheses mean the function is executed!
}

function changeCivilisationCallback(){
   //... 
}

// Now pass the changeCivilisationCallback to peakOil.
// Note: no changeCivilisationCallback parentheses because it is not 
// executed at this point.
// It will be excuted later inside peak oil.
peakOil(changeCivilisationCallback); 
In the example above, the chanceCivilisationCallback callback function is invoked by peakOil. Logic could be added to check if the energy returns from solar panels and wind farms were sufficient in which case another callback, other than changeCivilisationCallback could be added.

Configuration Object 
Instead of passing around a bunch of related properties...
function addCar(colour, wheelsize, regplate) {...}
Use a configuration object
function addCar(carConf) {...}

var myCarConf = {
    colour: "blue",
    wheelsize: "32",
    regplate: "00D98788"
};
addCar(myCarConf);
The use of a configuration object makes it makes it easier to write clean APIs that don't need to take a huge long list of parameters. They also means you are less likely to get silly errors if parameters are in the wrong order.
Closures
There are three ways to creats objects in Javascript: using literals, using the constuctor function and by using a closure.  What closures offer that the other two approaches do not is encapsulation.  Closures make it possible to hide away functions and variables.
var counter = function(count) {
    console.log(">> setting count to " + this.count);
    return {
        getCount: function(){
           return ++count;
        }
    }
}

mycounter = counter(0);
console.log(mycounter.getCount());  // outputs 1
console.log(mycounter.getCount());  // outputs 2
console.log(mycounter.getCount());  // outputs 3
console.log(mycounter.getCount());  // outputs 4

// Same again with offset this time.
mycounterWithOffset = counter(10);
console.log(mycounterWithOffset.getCount());  // outputs 11
console.log(mycounterWithOffset.getCount());  // outputs 12
console.log(mycounterWithOffset.getCount());  // outputs 13
console.log(mycounterWithOffset.getCount());  // outputs 14

Note: The closure is the object literal returned from annoymous function. It "closes" over the count variable. No-one can access it except for the closure. It is encapsulated. The closure also has a sense of state. Note also how the it maintains the value of the counter.  

Constructor Functions (Built in)
There are no classes in Javascript but there are construtor functions which use the new keyword syntax similar to the class based object creation in Java or other languages. Javascript has some built-in constructor functions. These include Object(), Date(), String() etc.
var person = new Object();  // person variable is an Object
person.name = "alex";  // properties can then be dynamically added

Constructor Functions (Custom)
When a function is invoked with the keyword new, it is referred to as a Constructor function. The new means that the new object will have a hidden link to value of the function's prototype member and the this keyword will be bound to the new object.
function MyConstrutorFunction() {
    this.goodblog = "dublintech.blogspot.com";
}
 
var newObject = new MyConstrutorFunction();
console.log(typeof newObject);    // "object"
console.log(newObject.goodblog);  // "dublintech.blogspot.com"

var noNewObject = MyConstrutorFunction();
console.log(typeof noNewObject);  // "undefined"
console.log(window.tastes);       // "yummy"
The convention is that constructor functions should begin with a capital letter. Note: if the new keyword is not used, then the 'this' variable inside the function will refer to the global object. Can you smell a potential mess? Hence why the capital letter convention for constructor functions is used. The capital letter means: "I am a constructor function, please use the new keyword".

Currying 
Currying is the process of reducing the number of arguments passed to a function by setting some argument(s) to predefined values. Consider this function.
function outputNumbers(begin, end) {
    var i;
    for (i = begin; i <= end; i++) {
        print(i);
    }
}
outputNumbers(0, 5);  // outputs 0, 1, 2, 3, 4, 5
outputNumbers(1, 5);  // outputs 1, 2, 3, 4, 5
Suppose, we want a similar function with a fixed "begin" value. Let's say the "begin" value was always 1. We could do:
function outputNumbersFixedStart(start) {
    return function(end) {
        return outputNumbers(start, end);
    }
}
And then define a variable to be this new function...
var outputFromOne = outputNumbersFixedStart(1);
outputFromOne(3);  1, 2, 3
outputFromOne(5);  1, 2, 3, 4, 5

Delete Operator
The delete operator can be used to remove properties from objects and arrays.
var person = {name: 'Alex', age: 56};
// damn I don't want them to know my age remove it
delete person.age;
console.log("name" in person);  // outputs true because it is still there
console.log("age" in person);   // outputs false


var colours = ['red', 'green', 'blue']
// is red really in the array?
console.log(colours.indexOf('red') > -1);  // outputs true. 
// remove red, it's going out of fashion!
delete colours[colours.indexOf('red')];
console.log(colours.indexOf('red') > -1);  // outputs false
console.log(colours.length) // length is still three, remember it's javascript!

You cannot delete global variables or prototype attributes.
console.log(delete Object.prototype)  // can't be deleted, outputs false
function MyFunction() {
    // ...
}
console.log(delete MyFunction.prototype) // can't be deleted, outputs false

var myglobalVar = 1;
console.log(delete this.myglobalVar)   // can't be delete, outputs false


Dynamic Arguments
Arguments for a function do not have to be specifed in the function definition
function myFunction(){
   // ... Note myfunction has no arguments in signature
   for(var i=0; i < arguments.length; i++){
       alert(arguments[i].value);
   }
}

myFunction("tony", "Magoo");  // any argument can be specified
The arguments parameter is an array available to functions and gives access to all arguments that were specified in the invocation.

for-in iterations
for-in loops (also called enumeration) should be used to iterate over nonarray objects.
var counties = {
    dublin: "good",
    kildare: "not bad",
    cork: "avoid"
}

for (var i in counties) {
    if (counties.hasOwnProperty(i)) { // filter out prototype properties
        console.log(i, ":", counties[i]);
    }
}

Functions are literals
This is an important one for people coming from a Java background. Functions do not need to have names. They can be anonymous, they can be passed into and returned from other functions without any needing a name - they can be treated literally. When a Java developer sees a function, they can't help thinking they are analogous to Java methods. But, Java methods can never be anonymous, they can be never be passed to or returned from other methods. They can be wrapped in an anonymous object defined on the fly; but they need that object that in many cases does nothing else - the methods themselves can never be treated literally. JavaScript ability to treat functions literally gives it a lot of expressive power.

Function declaration
In a function declaration, the function stands on its own and does not need to be assigned to anything.

function multiple(a, b) {
    return a * b;  
} // Note, no semi colan is needed 

Function expressions
When function is defined as part of something else's definition, it is considered a function expression. 

multiply = function multiplyFunction(a, b) {
    return a * b; 
}; // Note the semi colan should always be placed after the function

console.log(multiply(5, 10)); // outputs 50

In the above example, the function is named.  It can also be anonymous, in which case the name property will be a blank string.

multiply = function (a, b) {
   return a * b; 
}; // Note the semi colan should always be placed after the function  

console.log(multiply(5, 10)); // outputs 50

Functional Inheritance
Functional inheritance is mechanism of inheritance that provides encapsulation by using closures. Before trying to understand the syntax, take an example first. Suppose we want to represent planets in the solar system. We decided to have a planet base object and then several planet child objects which inherit from the base object. Here is the base planet object:
var planet = function(spec) {
    var that = {};
    that.getName = function() {
        return spec.radius;
    };
    that.getNumberOfMoons()= function() {
        return spec.numberOfMoons;
    };
    return that;
}
Now for some planets. Let's start with Earth and Jupiter and to amuse ourselves let's add a function for Earth for people to leave and a function to Jupiter for people arriving. Sarah Palin has taken over and things have got pretty bad!!!
var earth = function(spec) {
    var that = planet(spec);   // No need for new keyword!
    that.peopleLeave = function() {
        // ... people leave
    }
    return that;
}
var jupiter = function(spec) {
    var that = planet(spec);  
    that.peopleArrive = function() {
       // .. people arrive
    }
    return that;
}
Now put the earth and jupiter in motion...
    
var myEarth = earth({name:"earth",numberofmoons:1});
var myjupiter=jupiter({name:"jupiter",numberofmoons:66});
The three key points here:
  1. There is code reuse.
  2. There is encapsulation. The name and numberOfMoons properties are encapsulated.
  3. The child objects can add in their own specific functionality.
Now an explanation of the syntax:
  1. The base object planet accepts some data in the spec object.
  2. The base object planet creates a closures called that which is returned. The that object has access to everything in the spec object. But, nothing else does. This provides a layer of encapsulation.
  3. The child objects, earth and jupiter, set up their own data and pass it to base planet object.
  4. The planet object returns a closure which contains base functionality. The child classes receive this closure and add further methods and variables to it.
Hoisting 
No matter where var's are declared in a function, javascript will "hoist" them meaning that they behave as if they were declared at the top of the function.
mylocation = "dublin"; // global variable
function outputPosition() {
    console.log(mylocation);  // outputs "undefined" not "dublin"
    var mylocation = "fingal" ;  
    console.log(mylocation);  // outputs "fingal"
}
outputPosition(); 
In the function above, the var declaration in the function means that the first log will "see" the mylocation in the function scope and not the one declared in the global scope. After declaration, the local mylocation var will have the value "undefined", hence why this is outputted first.  Functions that are assigned to variables can also be hoisted.  The only difference being that when functions are hoisted, their definitions also are - not just their declarations.

Immediate Function Expressions
Immediate function expression are executed as soon as they are defined.
(function() {

    console.log("I ain't waiting around");

}());
There are two aspects of the syntax to note here.  Firsty, there is a () immediately after the function definiton, this makes it execute. Secondly, the function can only execute if it is a function expression as opposed to a function declaration. The outer () make the function an expression.  Another way to define a an immediate function expression is:
var anotherWay = function() {
    console.log("I ain't waiting around");
}()

JSON
JavaScript Object Notation (JSON) is a notation used to represent objects. It is very similar to the format used for Javascript Object literals except the property names must be wrapped in quotes. The JSON format is not exclusive to javascript; it can be used by any language (Python, Ruby etc). JSON makes it very easy to see what's an array and what's an object. In XML this would be much harder. An external document - such as XSD - would have to be consulted. In this example, Mitt Romney has an array describing who might vore for him and an object which is his son.
{"name": "Mitt Romney", "party": "republicans", "scary": "of course", "romneysMostLikelyVoters": ["oilguzzlers", "conservatives"], son : {"name":"George Romney"}}

Loose typing
Javascript is loosely typed. This means that variables do not need to be typed. It also means there is no complex class hierarchies and there is no casting.
var number1 = 50;
var number2 = "51";

function output(varToOutput) {
    // function does not care about what type the parameter passed is.
    console.log(varToOutput);
}
output(number1);  // outputs 50
output(number2);  // outputs 51

Memoization
Memoization is a mechanism whereby functions can cache data from previous executions.
function myFunc(param){
    if (!myFunc.cache) {
        myFunc.cache = {}; // If the cache doesn't exist, create it.
    }
    if (!myFunc.cache[param]) {
        //... Imagine the code to work out result below
        // is computationally intensive.
        var result = { 
            //... 
        };
        myFunc.cache[param] = result;  // now result is cached.
    }
    return myFunc.cache[param];
}

Method
When a function is stored as a property of an object, it is referred to as a method.
var myObject { 
    myProperty: function () {
       //...
       // the this keyword in here will refer to the myObject instance.
       // This means the "method" can read and change variables in the 
       // object.
    }
}

Modules
The goal of modules is to enable javascript code bases to more modular.  Functions and variables are collated into a module and then the module can decide what functions and what variables the outside world can see - in the same way as encapsulations works in the object orientated paradigms. In javascript we create modules by combining characteristics of closures and immediate function expressions.
var bankAccountModule = (function moduleScope() {
    var balance = 0; //private
    function doSomethingPrivate(){  // private method
        //...
    }   
    return { //exposed to public
        addMoney: function(money) {
             //...    
        },
        withDrawMoney: function(money) {
             //...
        },
        getBalance: function() {
            return balance;
    }
}());
In the example above, we have a bank account module:
  • The function expression moduleScope has its own scope. The private variable balance and the private function doSomethingPrivate, exist only within this scope and are only visible to functions within this scope.
  • The moduleScope function returns an object literal. This is a closure which has access to the private variables and functions of moduleScope. The returned object's properties are "public" and accesible to the outside world.
  • The returned object is automatically assigned to bankAccountModule
  • The immediate function ()) syntax is used. This means that the module is initialised immediately.
Because the returned object (the closure) is assigned to bankAccountModule, it means we can access the bankAccountModule as:
bankAccountModule.addMoney(20);
bankAccoumtModule.withdrawMoney(15);
By convention, the filename of a module should match its namespace. So in this example, the filename should be bankAccountModule.js.  

Namespace Pattern
Javascript doesn't have namespaces built into the language, meaning it is easy for variables to clash. Unless variables are defined in a function, they are considered global. However, it is possible to use "." in variables names. Meaning you can pretend you have name spaces.
DUBLINTECH.myName = "Alex"
DUBLINTECH.myAddress = "Dublin" 

Object Literal Notation
In javascript you can define an object as collection of name value pairs.   The values can be property values or functions.
var ireland = {
    capital: "Dublin",
    getCapital: function () {
        return this.capital;
    }
};

Prototype properties (inheritance)
Every object has a prototype object. It is useful when you want to add a property to all instances of a particular object. Suppose you have a constructor function, which representent Irish people who bought in the boom.
function IrishPersonBoughtInTheBoom(){
}

var mary = new IrishPersonBoughtInTheBoom ();
var tony = new IrishPersonBoughtInTheBoom ();
var peter = new IrishPersonBoughtInTheBoom ();
...
Now, the Irish economy goes belly up, the property bubble explodes and you want to add a debt property to all instances of this function. To do this you would do:
IrishPersonBoughtInTheBoom.prototype.debt = "ouch";
Then...
console.log(mary.debt);   // outputs "ouch"
console.log(tony.debt);   // outputs "ouch"
console.log(peter.debt);   // outputs "ouch"
Now, when this approach is used, all instances of IrishPersonBoughtInTheBoom share the save copy of the debt property. This means, that they all have the same value as illustrated in this example.  

Returning functions
A function always returns a value.  If return is not specified for a function, the undefined value type will be returned. Javascript functions can also return some data or another function.
var counter = function() {
    //...
    var count = 0;
    return function () {
        return count = count + 1;
    } 
}

var nextValue = counter();  
nextValue();   // outputs 1
nextValue();   // outputs 2
Note, in this case the inner function which is returned "closes" over the count variable - making it a closure - since it encapsulates its own count variable. This means it gets its own copy which is different to the variable return by nextValue.count.

this keyword
The this keyword in Java has different meanings, depending on the context it is used. In summary:
  • In a method context, this refers to the object that contains the method.
  • In a function context, this refers to the global object. Unless the function is a property of another object. In which case the this refers to that object.
  • If this is used in a constructor, the this in the constructor function refers to the object which uses the constructor function.
  • When the apply or call methods are used the value of this refers to what was explictly specified in the apply or call invocation.
typeof
typeof is a unary operator with one operand. It is used to determine the types of things (a bit like getClass() in Java). The values outputted by typeof are "number", "string", "boolean", "undefined", "function", "object".
console.log(typeof "tony");          // outputs string
console.log(typeof 6);               // outputs number
console.log(typeof false);                  // outputs boolean
console.log(typeof this.doesNotExist);   // outputs undefined if the global scope has no such var
console.log(typeof function(){});    // outputs function
console.log(typeof {name:"I am an object"});  //outputs object
console.log(typeof ["I am an array"]) // typedef outputs object for arrays
console.log(typeof null)              // typedef outputs object for nulls
Some implementations return "object" for typeof for regular expressions; others return "function". But the biggest problem with typeof is that it returns object for null. To test for null, use strict equality...
if (myobject === null) {
    ...
}

Self-redefining functions
This is a good performance technique. Suppose you have a function and the first time it is called you want it to perform some set up code that you never want to perfom again. You can execute the set up code and then make the function redefine itself after that so that the setup code is never re-excuted.
var myFunction = function () {
    //set up code only to this once
    alert("set up, only called once");
   
    // set up code now complete.
    // redefine function so that set up code is not re-executed
    myFunction = function() {
         alert("no set up code");
    }
}
myFunction();  // outputs - Set up, only called once
myFunction();  // outputs - no set up code this time
myFunction();  // outputs - no set up code this time
Note, any properties added to the set up part of this function will be lost when the function redefines itself. In addition, if this function is used with a different name (i.e. it is assigned to a variable), the re-definition will not happen and the set up code will re-execute.

Scope
In javascript there is a global scope and a function scope available for variables. The var keyword does not need to be used to define variable in the global scope but it must be used to define variable in the local function scope. When a variable is scoped to a local function shares the name with a global variable, the local scope takes precedence - unless var was not used to declare the local variable in which case any local references are pointing to the global reference. There is no block scope in javascript. By block we mean the code between {}, aka curly braces.
var myFunction = function () {
var noBlockScope = function ( ) {
    if (true) {  
        // you'd think that d would only be visible to this if statement
        var d = 24;    
    }
    if (true) { 
        // this if statement can see the variable defined in the other if statement
        console.log(d);  
    }
}
noBlockScope();

Single var pattern
You can define all variables used by a function in one place.  It is ensures tidy code and is considered best practise.
function scrum() {
    var numberOfProps = 2,
        numberOfHookers = 1,
        numberOfSecondRows = 2,
        numberOfBackRow = 3
    // function body...
}
If a variable is declared but not initialized with a value it will have the value undefined.
Strict Equality
In javascript it is possible to compare two objects using ==. However, in some cases this will perform type conversion which can yield unexpected equality matches. To ensure there is strict comparison (i.e. no type conversions) use the === syntax.
console.log(1 == true)    // outputs true
console.log(1 === true)   // outputs false
console.log(45 == "45")   // outputs true
console.log(45 === "45")  // outputs false

Truthy and Falsey
When javascript expects a boolean, you may specify a value of any type. Values that convert to true are said to be truthy and values that convert to false are said to be falsey. Example of truthy values are objects, arrays, functions, strings and numbers:
// This will output 'Wow, they were all true'
if ({} && {sillyproperty:"sillyvalue"} && [] &&
        ['element'] && function() {} && "string" && 89) {
   console.log("wow, they were all true");
}
Examples of falsey values are empty strings, undefined, null and the value 0.
// This will out put: 'none of them were true'
if (!("" || undefined || null || 0)) {
    console.log("none of them were true");
}

Undefined and null
In javascript, the undefined value means not initialised or unknown where null means an absence of a value.

References
  1. JavaScript patterns Stoyan Stefanov
  2. JavaScript, The Definitive Guide David Flanagan
  3. JavaScript, The Good Parts Doug Crockford.

Friday, October 14, 2011

Javascript Closure's and Currying!

Closures are a powerful and important feature of Javascript. Before trying to understand the syntax of how to create one it's important to understand just why they are an important feature of the language. Firstly closures are a way of creating objects. But, so what? Javascript already provides two ways to do this: Object literals and Constructor functions. So what's wrong with these mechanisms? Well they do not provide any sort of encapsulation. Get a handle to an object created via the literal object approach or the constructor function approach and you can pretty much can change anything in the object.

Watch this poor literal object's encapsulation dreams smash...
myObject = {
    myProperty:"I wish I was encapsulated"
}
console.log(myObject.myProperty);  //outputs I wish I was encapsulated
myObject.myProperty = "sorry mate you're note";
console.log(myObject.myProperty);  //outputs sorry mate you're note
As for the Constructor function...
var Person = function(name) {
    this.name = name;
    this.speak = function () {
        return "I am " + this.name;
    }
}

var tony = new Person("Tony");
console.log(tony.speak());  // outputs I am Tony

// Tony's encapsulation dreams are going to get smashed.
tony.name = "Fatso";
console.log(tony.speak());  // outputs I am fatso
This is awful. Put yourselves in Tony's shoes and think about how he feels. This lack of encapsulation causes problems. Some programmers used the convention of an underscore before a property (as in _name) to try to indicate they wished they could make a property private but they couldn't. The underscore was saying: "please, please don't touch me".  But who wants to engineer logical systems around emotional pleas?

Closures provide a mechanism for encapsulating objects. You want to encapsulate Tony's name (and every other person's name) do this:
var person = function(name) {
    console.log(">> setting name to " + this.name);
    return {
        getName: function(){
           return name;
        } 
    }
}
var tony = person("Tony");  // outputs setting name to Tony
console.log(tony.getName());  // outputs Tony
tony.name = "Fatso"   // it won't change the name in the closure
console.log(tony.getName()); // still outputs Tony
WOW! at last some encapsulation. Let me try to explain... The outer function returns an Object literal. This lives longer than the outer function. The outer function effectively ends as soon as person("tony") is finished. The object literal lives longer because it is returned. Properties and methods in the object literal can access variables in the outer function. Just like the way any inner function can access variables in the outer function. Now, when the object literal is returned it "closes" over the values of the variables in the outer function it can access. Effectively, getting keeping a copy of them. It would be the exact same for an inner function if it was returned. What is returned is called the closure. The outside world cannot directly access what the closure closes over. It can only access what the closure itself advertises to the outside world. In this case, that is just one function getName(). This all means we can make encapsulated person objects.

Currying
Currying is the process of reducing the number of arguments passed to a function by setting some argument(s) to predefined values.  Consider this function...

function outputNumbers(begin, end) {
    var i;
    for (i = begin; i <= end; i++) {
        print(i);
    }
}
outputNumbers(0, 5);  // outputs 0, 1, 2, 3, 4, 5
outputNumbers(1, 5);  // outputs 1, 2, 3, 4, 5
Now suppose we want a similar function with a fixed "begin" value.  Let's say the "begin" value was always 1.  We could do:
function outputNumbersFixedStart(start) {
    return function(end) {
        return outputNumbers(start, end);
    }
}

And then defined a variable to be this new function...
var outputFromOne = outputNumbersFixedStart(1);
outputFromOne(3);  1, 2, 3
outputFromOne(5);  1, 2, 3, 4, 5

As can be seen, the number of arguments has been reduced from 2 to 1. And this has been enabled because the argument that has been eliminated has been set to a fixed value, in this case its value is 1.

Currying works by creating a closure that holds the original function and the arguments to curry.  A generic solution to currying is to add a "curry" function to every function in our code by augmenting function's prototype to include a curry function.  
Function.prototype.curry = function() {
    if (arguments.length<1) {
        return this; //nothing to curry with - return function
    }
    var that = this;
    var slice = Array.prototype.slice;
    var args = slice.apply(arguments);
    return function() {
        var innerFunctionSlice = slice.apply(arguments);
        return that.apply(null, args.concat(slice.apply(arguments)));
    }
}
This curry function can be applied to any function.
var outputFromZeroCurried = outputNumbers.curry(0);  
var outputFromOneCurried = outputNumbers.curry(1);   

outputFromZeroCurried(3);  // outputs 0, 1, 2, 3
outputFromOneCurried(5);  // outputs 1, 2, 3, 4, 5
Note: One thing to bear in mind in the curry prototype function is that the value of arguments in the outer function is different to the value of arguments in inner function.  When outputNumbers.curry(0) is invoked, arguments in the outer function is {0}. When outputFromZeroCurried(3) is invoked, arguments for inner function is {3}, but arguments for the outer function is still {0}. Essentially, 'arguments' in the outer function refers to arguments passed to the outer function; 'arguments' for the inner function refers to arguments for the inner fuction.

This smells like a Curry!

Monday, October 10, 2011

Are you confused by "this" Javascript?

George Bush found many things confusing!
The keyword "this" is important in javascript but it is also confusing.  The reason is because it's not always easy to ascertain what it actually means. It has different values depending on where it is in a piece of code and more importantly what context the code is invoked in.

In 'Javascript: The Good Parts', Javascript Guru Doug Crockford describes four different invocation patterns, the "this" parameter is initialised differently in all four patterns: the method invocation pattern, the function invocation patter, the constructor invocation pattern and the apply invocation pattern

The Method Invocation Pattern
When a function is property of an object in javascript it is a method. When the method is invoked, the 'this' refers to that object.  For example, in the code below the property getName is an anonymous function.  If the anonymous function wishes to refer to the name variable it uses the 'this' notation.
var myObject = {
    name: "Staveley",
    getName: function () {
        return this.name;
    }
};

console.log(myObject.getName());// Staveley.

It is worth stressing the importance of 'this' in the example above.  If it is not used, the name will be the global one.
name="GlobalName";
var myObject = {
    name: "Alex",
    getName: function () {
        return name; // refers to name in global namespace.
    }
};
console.log(myObject.getName());// Outputs GlobalName not Alex.

The Function Invocation Pattern
When a function is defined not as a method but just as a function (i.e. there is no property defining it in an object),  the keyword 'this' refers to the the global object.
var getNameFunction = function() {
    name: "Alex";
    console.log(">>getNameFunction(),name=" + this.name);  
};
// Invoking getNameFuction() outputs: undefined.  
// Because, this is equal to the global object 
// which has no name property.
getNameFunction(); 

When another object has a property which calls the getNameFunction, the 'this' inside the
getNameFunction refers to that other object.
var obama = {
    name: "obama"
};

obama.getName = getNameFunction;
obama.getName();  // outputs obama!

But, an inner function does not share the method's access to the object as its 'this' is bound to the wrong value.
obama.getFullName = function() {
    var outputName = function() {
        console.log("barack " + this.name);
    };
    outputName();
} 
// Invoking getFullName() outputs barack undefined. Why? 
// Because the innerfunction's 'this' refers to the global variable. 
// The global variable has no name property.
obama.getFullName(); 

The solution is to assign another variable to the value this. By convention this variable takes the name 'that'.
obama.getFullName = function () {
    var that = this;
    var outputName = function() {
        console.log("barack " + that.name);
    };
    outputName();
};
obama.getFullName(); // outputs barak obama

Inner functions confused Obama!
The Constructor Invocation Pattern
Objects can be easily defined using object literal syntax. However, sometimes when many objects of the same type need to be defined there is a need for consistency. There is also a need to avoid repetition. Two good reasons to use constructor functions! 
var Car = function(colour, reg){
    this.colour= colour;  // this refers to the object being created.
    this.reg = reg;
};

var myRedCar = new Car("Red", "00D901");
var myGreenCar = new Car("Green", "00D902");
var myBlueCar = new Car("Blue", "00D903");  

// Now test those assignments worked. 
console.log(myRedCar.colour + ", " + myRedCar.reg);   // outputs Red, 00D901
console.log(myGreenCar.colour + ", " + myGreenCar.reg); // outputs Green, 00D902
console.log(myBlueCar.colour + ", " + myBlueCar.reg);  // outputs Blue, 00D903

Now suppose we want to add a method common to all 'Car' objects. We do:
Car.prototype.getColour = function() {
    console.log(">> getColour(), colour = " + this.colour);
};

In this case, the 'this' refers to the object created with the new prefix
myRedCar.getColour();  // outputs Red
myGreenCar.getColour(); // outputs Green
myBlueCar.getColour();  // outputs Blue

The Apply Invocation Pattern
When Apply (or Call) is used we are allowed to choose the value of 'this'.  To do this,
we simply specify it as an argument.
myRedCar.getColour.apply(myGreenCar);  // outputs green
myGreenCar.getColour.apply(myRedCar); // outputs red

References:
1. Brilliant tutorial on Javascript objects: http://helephant.com/2008/08/17/how-javascript-objects-work/
2. Douglas Crockford: http://javascript.crockford.com/javascript.html