简体   繁体   English

两次声明javascript函数

[英]Declaration of a javascript function twice

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 : 这是HTML代码:

<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 ? 我如何才能使它们同时工作而不将所有功能都集成在一起?

There is no such thing as method/function overriding in javascript. 在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. Javascript确实具有switch语句,因此这可能很适合您的问题。 It would be a little neater than a large if/else block. 这将比大的if / else块更整洁。 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');
  }
}

Just imagine you are java script runtime... How will you detect such ambiguity? 试想一下您是Java脚本运行时...您将如何检测到这种歧义? 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" 这是简单的JS对象,具有键“测试”的已定义功能

And access the functions by yourNamespace1.test(...) and yourNamespace2.test(...) 并通过yourNamespace1.test(...)yourNamespace2.test(...)访问函数

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
   }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM