Tuesday, September 29, 2015

JavaScript Contexts and Scopes

It took me a LONG LONG LONG time to figure out why my code re-factorization wouldn't work in JavaScript. I finally found the page ryanmorr.com/understanding-scope-and-context-in-javascript which led me in the right direction and this developer.mozilla.org page which showed me a more concrete example.

Basically, I wasn't using the "bind" function for my object references.


// Define the class.
var Construct = Construct  || (function() 
{
    // Constructor.
    var Construct = function(name) {};
   
    // Additional functions.
    Construct.prototype = 
    {
        sayHello: function() { alert("Hello"); }
        schedule_WRONG: function() { setTimeout(this.sayHello, 1500); },
        schedule_RIGHT: function() { setTimeout(this.sayHello.bind(this), 1500); },
    };
   
    // Return the type.
    return Construct;
})();

$(function()
{
    // Construct the object.
    var f = new Construct();
    f.schedule();

});