Javascript - set a variable using concatenation of strings

Chris Schmitz picture Chris Schmitz · Oct 31, 2013 · Viewed 25k times · Source

Is it possible to set a variable by concatenating two strings together to form the name?

If at all possible I'd like to determine what variable to set based on the class names of the objects that the user clicks. I know I can hard code a bunch of if/else if statements, but it would be really cool if I could reference the variables indirectly. I was thinking something like this:

var owner_read;
var group_read;

function setVariableIndirectly(object){
    var second = object.className; // returns "read"
    var first = object.parentElement.className; // returns "group"

    first + "_" + second = "set this as the new variable";
}

Is there any way of doing this??

EDIT:

Here's the html that the data is coming in from.

<p class="owner">
    <span class="read" onclick="permissionClick(this)">r</span>
    <span class="write" onclick="permissionClick(this)">w</span>
    <span class="execute" onclick="permissionClick(this)">x</span>
</p>

Answer

Brian Peacock picture Brian Peacock · Oct 31, 2013

This is possible but you have to be wary of context and scope.

1. To set variable with global scope in browser environment:

window[str1 + str2] = value

2. To set variable with global scope in node environment:

global[str1 + str2] = value

3. Within a closure and scoped within that closure:

this[str1 + str2] = value

Within the closure, global and window will still set the global. Note that if you are within a function that is being called, 'this' could refer to another object.