Example: Closure Context

by Matthew Marcus

JavaScript

function Bar(){
    this.id = Math.round(Math.random()*10000);
    this.listener = null;
};

Bar.prototype.register = function(listen){
    this.listener = listen;
};

Bar.prototype.fire = function(){
    setTimeout(this.listener, 2000);
};

function Foo(){
    
}

Foo.prototype.createBar = function(cb){
    cb(new Bar());
};

var bars = [];
for (var i = 1; i <= 10; i++){
    var foo = new Foo();
    foo.createBar(function(bar){
        bar.register(function(){
            console.log('FIRED! ', bar.id);
        });
        bars.push(bar);
    });
}

console.log(bars[3].id);
bars[3].fire();