Reputation: 2852
Let's say I want to make a JavaScript function which sets variables to numbers, using the following format. It would not work, but why exactly? How could it be made to work?
function variableSet(varName, varValue) {
varName = varValue;
}
The idea is to create a variable with the name used as a parameter, and give it the value of the second parameter. How could this be done?
Upvotes: 1
Views: 68
Reputation: 6483
Not sure I understand your question. But if you need to give a variable name and it's value to overwrite the variable, it can be done like that:
this[varName]=varValue;
In this case "this" is your context, in which variable was defined. If you need to provide the other context, you can put it as other parameter, so function will look like this:
function variableSet(varName, varValue, context) {
context[varName]=varValue;
Upvotes: 2