Still celebrating National IT Professionals Day with 3 months of free Premium Membership. Use Code ITDAY17

x
?
Solved

JavaScript function with variable value in the name

Posted on 2014-03-19
8
Medium Priority
?
488 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
8 Comments
 
LVL 33

Accepted Solution

by:
Big Monty earned 1600 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
Linux Academy Android App Now Supports Chromecast

We have some fantastic news for our Android fans. We’re so excited to announce that the Linux Academy Android app is now available with Chromecast support. That’s right – simply download the latest update of the Linux Academy App and start casting your favorite course videos!

 
LVL 33

Assisted Solution

by:Big Monty
Big Monty earned 1600 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 260 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 140 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

Congratulations! You’re Certified – Now What?

Starting a new career can be overwhelming. Becoming certified in your field of expertise is a great start, but where do you go from here?  Here are some tips to help you on your career journey.

Question has a verified solution.

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

In this article you'll learn how to use Ajax calls within your CodeIgniter application. To explain this, I'll illustrate how to implement a simple contact form to allow visitors to send you an email through your web site.
Introduction JSON is an acronym for JavaScript Object Notation.  It is a text-string data transport mechanism, capable of representing simple or complex data structures in a consistent and easy-to-read manner.  Similar in concept to XML, but more e…
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)
The viewer will learn the basics of jQuery including how to code hide show and toggles. 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…

721 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