Wednesday, December 23, 2009

Javascript Bind Function Without a Framework

Since writing this question and learning just a bit about contexts in Javascript, I set out to write my own bind method without using a Framework like JQuery nor Prototype. Here is one that works, though I must admit that I've only tested it on Firefox.
function bind(method, obj, param1, param2, param3) {
    var retVal = function() {
        method.call(obj, param1, param2, param3)
    };
    return retVal;
}
Here's some test code, just to get the idea
function Blah() {}
Blah.prototype.blah = function(param) {
    alert("param=" + param + " thing=" + this.thing);
};

Blah.prototype.thing = "this is the thing"
b = new Blah()
window.setTimeout(bind(b.blah, b, "some-param"), 10);
Example is not the best, but the bind method is solid.

No comments: