Functional Programming

I’m almost done with a functional prototype of the server.

Before I add the finishing touches I’m turning my horribly messy code into clean OOP code. However, encapsulation has introduced some problems I haven’t encountered before and has taught me about functional programming in javascript!

Basically, I was using Jquery to attach a function to the onlick event of a piece of text representing a connection. It would display the connections details in the HTML of the page. Therefore, within the onclick function I had to access the properties of a javascript object. In the old procedural code, there was nothing wrong with this, because these objects were in the global scope. However, upon putting the code within an object dedicated to changing the HTML of the page, it no longer worked. Here are simplified examples.

Old code:

 
function displayHTML()
{
    // ... Some code ...
}

$("html-element").click(function()
{
    displayHTML();  // Fine! This function was declared in global scope!
}

New code:

function htmlObject()
{
    this.displayHTML = function()
    {
        // ... some code ...
    }

    $("html-element").click(function()
    {
        this.displayHTML();  // Won't work! 
    }
}

It’s obvious why this doesn’t work, but I was struggling to think of a way of using Jquery from within an object like this without exposing the variables within the object to the global scope (which completely defeats the purpose). So I did a bit of googling and these two pages helped fill in the gaps in my knowledge!

So the answer seems to be to define a function within the object but not as a property of the object. This type of declaration will ensure the function definition persists as long as the click() function needs it, because it is a closure. I wasn’t aware of this concept before.

Apparently this is a core concept of functional programming which lies at the heart of both Jquery and Node.js, so it was definitely useful to know this.

Advertisements