I need to declare a function 2 times with a different treatements let me explain more the overwritting :
function test(var){
//treatments
}
function test(var){
alert("something" +var);
}
and here is the HTML code :
<select name="choices" onchange="test(this)">
<option value="1">test1</option>
<option value="2">test2</option>
</select>
how can I make them working both without making everything in one function ?
-
3You can't have two functions with the same name. What makes you think you need to have the function named the same thing? What differentiates when you need to call which one?Dave Newton– Dave Newton2013年02月11日 22:02:15 +00:00Commented Feb 11, 2013 at 22:02
-
I am using a volusion website and I don't have access to modify a function , and I need to open a modal dialog in the execution , I can't modify even the html code , I have one place to put a javascript code in the head of page , does it make sence ?user2039991– user20399912013年02月11日 22:04:58 +00:00Commented Feb 11, 2013 at 22:04
3 Answers 3
There is no such thing as method/function overriding in javascript. Whichever function is defined last takes precedence. You could split the logic into different functions but you would need some sort of main function that decides which one to use.
Javascript does have switch statements though, so that might be a good fit for your problem. It would be a little neater than a large if/else block. Something like the following might work.
function test(el){
switch(el.value){
case 1:
alert('option 1 selected');
break;
case 2:
alert('Option 2 selected');
break;
default:
alert('Another option was selected');
}
}
4 Comments
Just imagine you are java script runtime... How will you detect such ambiguity? Answer is no. You can't define functions with same signature in the same scope.
But my advice is to use some kind of "namespaces":
var yourNamespace1 = {
test: function(var) {
//treatments
}
};
var yourNamespace2 = {
test: function(var) {
alert("something" +var);
}
};
It is simple JS objects with defined functions for key "test"
And access the functions by yourNamespace1.test(...) and yourNamespace2.test(...)
Comments
You're looking to have different behavior based on the choice in the dropdown. Here's one way to do that:
<select name="choices" onchange="test(this)">
<option value="1">test1</option>
<option value="2">test2</option>
</select>
function test(el)
{
var num = el.options[el.selectedIndex].value;
if (num == 1)
{
// case 1
}
else if (num == 2)
{
// case 2
}
}