Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript create variable from its name

Tags:

javascript

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"}]
like image 596
Marek Sebera Avatar asked Aug 11 '11 14:08

Marek Sebera


1 Answers

try:

this[name] = "value";

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:

var foo = {};
foo['bar-baz'] = 'fizzbuzz';
alert(foo.bar-baz); //this will not work because `-` is subtraction
alert(foo['bar-baz']); //this will work fine

If you are creating a new object literal, you can use string literals for the names for values with special characters:

var foo  = {'bar-baz':'fizzbuzz'};

But you will not be able to use variables as the key within an object literal because they are interpreted as the name to use:

var foo = 'fizz';
var bar = { foo:'buzz' }
alert( bar.fizz ); //this will not work because `foo` was the key provided
alert( bar.foo ); //alerts 'buzz'

Because other answerers are mentioning eval, I will explain a case where eval could be useful.

Warning! Code using eval is evil, 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 foo in the global context attaches the new variable to the global object (typically window). In a closure, however, the variable created by var foo exists 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:

var container = {};
container[foo] = 'bar';

So with that all being said, if a dynamic variable name is required and a container object is not able to be used, eval can be used to create/access/modify a dynamic variable name.

var evalString = ['var', variableName, '=', String.quote(variableValue), ';'].join(' ')
eval( evalString );
like image 115
zzzzBov Avatar answered Oct 04 '22 13:10

zzzzBov