Reputation: 198
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:
var methodHandler = {
'a-key': function () {
aVariable = document.getElementById('a-container');
}
}
function sample() {
var aVariable;
methodHandler['a-key']();
console.log(aVariable);
}
sample();
Upvotes: 0
Views: 65
Reputation: 69346
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}
Upvotes: 0
Reputation: 629
Because of scoping, you can't really do it that way. However, you could restructure it like this and get a similar result:
var methodHandler = {
'a-key': function () {
return document.getElementById('a-container');
}
}
function sample() {
var aVariable = methodHandler['a-key']();
console.log(aVariable);
}
sample();
Upvotes: 2