Skip to content
Advertisement

Passing variables to object key function and back to requesting function

Seems like I can only create a global variable for this to work but here is what would be ideal. I would like to pass a variable to an object which has keys that reference functions. In the function I am referencing I would like to set either that variable or one that was defined within the function that called it and pass it back:

jsfiddle

var methodHandler = {
    'a-key': function () {
        aVariable = document.getElementById('a-container');
    }
}

function sample() {
    var aVariable;

    methodHandler['a-key']();
    console.log(aVariable);
}

sample();

Advertisement

Answer

You should use the this element. The this element, when referenced inside a function of the object, represents the object itself, so doing this.foo = 1 will actually create a property called foo with the value of 1 in your object.

Here is the correct form of the code:

var methodHandler = {
    'a-key': function () {
        this.aVariable = document.getElementById('a-container');
        return this.aVariable;
    }
}

function sample() {
    // You can do this:
    methodHandler['a-key']();
    console.log(methodHandler['aVariable']);

    // Or you can do this instead:
    console.log(methodHandler['a-key']());
}

sample();

When you call methodHandler['a-key'](), the property aVariable will be set in your object, so if you log the object you’ll see this:

console.log(methodHandler);
// Object {a-key: function, aVariable: div#a-container}
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement