Mar 16, 2009

Function.createDelegate

function greet(message) {
        alert(message + ", " + this.name);
    }

    var instance = { name: "fred" };
    
    //when you create a delegate, "this" in the delegate function body
    //refer to the instance passed in
    var greetSomeone = Function.createDelegate(instance, greet);
    greetSomeone("hello");
    /*
    Function.createDelegate = function Function$createDelegate(instance, method) {
    /// 
    /// 
    /// 
    /// 
    var e = Function._validateParams(arguments, [
        { name: "instance", mayBeNull: true },
        { name: "method", type: Function }
    ]);
    if (e) throw e;
    return function() {
        return method.apply(instance, arguments);
    }
}