Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jquery variables variable

There exist some concept like variables variable to print variable names or call functions dynamically:

http://php.net/manual/en/language.variables.variable.php

Thanks in advance.

like image 244
josoroma Avatar asked Sep 16 '10 02:09

josoroma


2 Answers

The closest JavaScript equivalent is bracket notation, for example:

var obj = { myMethod: function() { alert("Hello!"); } };
var func = "myMethod";
obj[func](); //equal to obj.myMethod();

You can test it out here, in JavaScript calling these two is equivalent:

object.property
object["property"];

And the latter allows you to use a variable, to get any property or method you want.

To be clear this is a JavaScript behavior, there's nothing specific to jQuery about it.

like image 171
Nick Craver Avatar answered Sep 20 '22 00:09

Nick Craver


In javascript you can use a similar aproach.

$a = "hello";
$['hello'] = 'world';
$[$a];
alert($a + " " + $[$a]); // alerts "hello world"

See in jsfiddle.

like image 31
Topera Avatar answered Sep 18 '22 00:09

Topera