Search code examples
javascriptobjectprototypeextend

Javascript Object custom functions


Possible Duplicate:
Javascript closure inside loops - simple practical example
Javascript infamous Loop problem?

I have a base function, that I want to control what ends up being like a "bumpbox". My goal is to instantiate multiple instances of this and give each of the declared variables a custom config.

The object looks like this:

Project.Modules.bumpbox = function(in_trigger, container) {

    var config = {

        'speed': 500,
        'easing' : false,//will 
        'in_callback': false,
        'out_callback' : false,
        'visible': false,
        'out_trigger' : $('#bumpbox_out_trigger'),//this is set by default only change if you know what you are doing!
    };

    this.test = function() {

        //this should be the default function. 

    };

And then, from another file, I want to instantiate an instance like new Project.Modules.Bumpbox() and overwrite the test function.

var bumpbox_controllers = {

            "map" : new Project.Modules.bumpbox($('#navigation_top li.map'), $('.bumpbox.map')),
            "contact" : new Project.Modules.bumpbox($('#navigation_top li.contact'), $('.bumpbox.contact')),
            "about" : new Project.Modules.bumpbox($('#navigation_left li.about'), $('.bumpbox.about')),
            "team" : new Project.Modules.bumpbox($('#navigation_left li.team'), $('.bumpbox.team')),
            "careers" : new Project.Modules.bumpbox($('#navigation_left li.careers'), $('.bumpbox.careers')),
            "services" : new Project.Modules.bumpbox($('#navigation_left li.services'), $('.bumpbox.services'))
        };

and then I want to loop through each of those and set a custom test() function in each like this:

    bumpbox_controllers[i]['test'] = function() {

        alert(i);
    }

But when I run this code, it will switch all of the elements to the last i value called, in this case "service", not giving each a unique element.


Solution

  • You seem to need a closure for your loop:

    for (var controller in bumpbox_controllers) {
        bumpbox_controllers[controller] = (function(i) {
            // creating a new context for i
            return function() {
                alert(i); // access the i in scope, not the controller
            }
        })(controller);
    }