Solved

JavaScript function with variable value in the name

Posted on 2014-03-19
8
473 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 32

Accepted Solution

by:
Big Monty earned 400 total points
Comment Utility
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 32

Expert Comment

by:Big Monty
Comment Utility
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
Comment Utility
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
 
LVL 32

Assisted Solution

by:Big Monty
Big Monty earned 400 total points
Comment Utility
in short, no, you cannot embed a variable name within a JS function in the manner you are attempting
0
Better Security Awareness With Threat Intelligence

See how one of the leading financial services organizations uses Recorded Future as part of a holistic threat intelligence program to promote security awareness and proactively and efficiently identify threats.

 
LVL 3

Author Comment

by:Pedro Chagas
Comment Utility
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
Comment Utility
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
Comment Utility
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
Comment Utility
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

How to run any project with ease

Manage projects of all sizes how you want. Great for personal to-do lists, project milestones, team priorities and launch plans.
- Combine task lists, docs, spreadsheets, and chat in one
- View and edit from mobile/offline
- Cut down on emails

Join & Write a Comment

How to build a simple, quick and effective accordion menu using just 15 lines of jQuery and 2 css classes
This article discusses how to create an extensible mechanism for linked drop downs.
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)

762 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

Need Help in Real-Time?

Connect with top rated Experts

9 Experts available now in Live!

Get 1:1 Help Now