Search code examples
javascriptclosuresy-combinator

can i use y-combinator to get object reference for this closure?


this closure works:

var o = {
    foo: 5
};

o.handler = function(obj){
    return function() {
        alert(obj.foo);
    };
}(o);

o.handler(); //alert('5')

is it possible to define handler in-line, perhaps with something similar to a y-combinator operation?

var o = {
    foo: 5,
    handler: function(obj){
        return function() {
            alert(obj.foo);
        };
    }(o); //pointer to o? -----------------------------
};

out of academic curiosity, I'm not trying to do this in production code

intro to the y-combinator


Solution

  • No, this is not possible, because at the time of definition of the object literal, the variable o is undefined, and the this reference at the time of definition doesn't reference o.

    If you used a temporary reference to this in the outer function and passed it into the closure, it would work, but you would not be able to pass in an object to get the foo property out of.

    var o = {
        foo: 5,
        handler:function(){
            var self = this;
            return function() {
                alert(self.foo);
            };
        }
    };
    
    var h = o.handler();
    h();