In PHP we can do this:
$variable = "name_of_variable";
$this->{$variable} = "somevalue";
how to do this in javascript?
where use case should look like:
function Apple(){
var name = "variable_name";
this.(name) = "value";
}
console.log(new Apple());
to output
[Apple: {variable_name:"value"}]
try:
All objects can use dot and array notation for variable access.
Also note, this will allow you to create name value pairs that are inaccessible via dot notation:
If you are creating a new object literal, you can use string literals for the names for values with special characters:
But you will not be able to use variables as the
keywithin an object literal because they are interpreted as the name to use:Because other answerers are mentioning
eval, I will explain a case whereevalcould be useful.Warning! Code using
evalisevil, proceed with caution.If you need to use a variable with a dynamic name, and that variable does not exist on another object.
It’s important to know that calling
var fooin the global context attaches the new variable to the global object (typicallywindow). In a closure, however, the variable created byvar fooexists only within the context of the closure, and is not attached to any particular object.If you need a dynamic variable name within a closure it is better to use a container object:
So with that all being said, if a dynamic variable name is required and a container object is not able to be used,
evalcan be used to create/access/modify a dynamic variable name.