Solved

JavaScript function with variable value in the name

Posted on 2014-03-19
8
479 Views
Last Modified: 2014-03-22
Hi E's, I want to know if it is possible do this thing, and how:
I have this 3 functions, cena1(), cena2() and cena3(), and I will call the function of the value of the variable number (var number = x), x can be 1,2 or 3.
So, when I call the function cena?(), I have to put the value of the variable in the name of the function in (?).
How I do that?

The best regards, JC
0
Comment
Question by:Pedro Chagas
8 Comments
 
LVL 33

Accepted Solution

by:
Big Monty earned 400 total points
ID: 39939515
Store your functions in an object instead of making them top level.

var cena = {
    cena1: function() { },
    cena2: function() { },
    cena3: function() { }
};
Then you can access them like any other object:

cena['cena' + num]();
You could also access them directly from the window object…

window['cena' + num]();
… and avoid having to store them in an object, but this means playing in the global scope which should be avoided.
0
 
LVL 33

Expert Comment

by:Big Monty
ID: 39939518
personally, i would just use the index number as a javascript parameter, and define the different sections from within one function, instead of playing around with the global scope so much...
0
 
LVL 3

Author Comment

by:Pedro Chagas
ID: 39940400
Hi @big_monty, thanks for your attention.
Tell me one thing please, is not possible put the variable directly in the name of the function, something like cena'number'(){...}?
I believe your solution is the best when I start the project (beginning), my project are in the end, and I need just to know how I put the name of the variable in the name of the function.
Thank you.
~JC
0
DevOps Toolchain Recommendations

Read this Gartner Research Note and discover how your IT organization can automate and optimize DevOps processes using a toolchain architecture.

 
LVL 33

Assisted Solution

by:Big Monty
Big Monty earned 400 total points
ID: 39940410
in short, no, you cannot embed a variable name within a JS function in the manner you are attempting
0
 
LVL 3

Author Comment

by:Pedro Chagas
ID: 39940462
In that case, I have to follow your solution.
I will try later, and I give you feedback.
Thank you again.
~JC
0
 
LVL 3

Author Comment

by:Pedro Chagas
ID: 39941142
Hi, I try your solution and seems work well, but I have a problem in my bellow code:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
</head>
<body>
<script>
var numero = 1;

var cena = {
    cena1: function() { num1(); },
    cena2: function() { num2(); },
    cena3: function() { num3(); }
};

cena['cena' + numero]();

function funcao(){
    function num1(){
        document.write("1");
    }
    function num2(){
        document.write("2");
    }
    function num3(){
        document.write("3");
    }
    
}

</script>
</body>
</html>

Open in new window

In Firebug the problem is "num1 is not defined".
num1, 2 or 3, are inside function "funcao", seems not be a global function.
I make this question because this code example is the closest replica to my real code, and I have to find a solution.
Is there a solution, or should I open a new question for this new problem?

~JC
0
 
LVL 14

Assisted Solution

by:Pierre Cornelius
Pierre Cornelius earned 65 total points
ID: 39941559
Try this instead:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
</head>
<body>
<script type="text/javascript">
var numero = 1;

function funcao(){
    this.num1 = function (){document.write("1");}	
    this.num2 = function (){document.write("2");}	
    this.num3 = function (){document.write("3");}   
}
var funcs = new funcao();
var cena = [
    function cena1() { funcs.num1(); },
    function cena2() { funcs.num2(); },
    function cena3() { funcs.num3(); }
];

cena[numero-1]();

</script>
</body>
</html>

Open in new window


or even simpler:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
</head>
<body>
<script type="text/javascript">
var numero = 1;

var cena = [
    function cena1() { document.write("1");},
    function cena2() { document.write("2");},
    function cena3() { document.write("3");}
];

cena[numero-1]();

</script>
</body>
</html>

Open in new window


I do agree with Bi Monty however. Something like this would have been better:
function better_cena(anumero) {
	switch (anumero)
	{
		case 1: document.write("Execute code if numero = 1"); break;
		case 2: document.write("Execute code if numero = 2"); break;
		case 3: document.write("Execute code if numero = 3"); break;
		default: document.write("Unsupported numero:"+anumero);
	}
}

Open in new window

You can call like this:
  better_cena(1);
  better_cena(2);
  better_cena(3);
  better_cena(4);
0
 
LVL 9

Assisted Solution

by:Sar1973
Sar1973 earned 35 total points
ID: 39941705
If you have a generic function that uses an argument, call it cena(myArg) and declare it as cena(x) {.....}, using directly x as an arguments of the lines of code inside the function.
Is that what you're asking for...?
0

Featured Post

Master Your Team's Linux and Cloud Stack

Come see why top tech companies like Mailchimp and Media Temple use Linux Academy to build their employee training programs.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Title # Comments Views Activity
age from date of birth 4 43
Javasctipt 2 26
Call Controller Action Method from ASPX 2 16
how can i get the string decoded ? 2 14
There are a couple ways to attach a JavaScript function to dynamically created elements. You can make a new script for each element as it’s created or you can use delegation. Delegation allows a single script that is added at page creation to mat…
Boost your ability to deliver ambitious and competitive web apps by choosing the right JavaScript framework to best suit your project’s needs.
The viewer will learn how to dynamically set the form action using jQuery.
The viewer will learn the basics of jQuery, including how to invoke it on a web page. Reference your jQuery libraries: (CODE) Include your new external js/jQuery file: (CODE) Write your first lines of code to setup your site for jQuery.: (CODE)

821 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question