当存在两个同名函数时,为什么只有第二个函数运行?

Why does only the second function run when two functions with the same name exist

本文关键字:函数 为什么 运行 第二个 存在 两个      更新时间:2023-09-26

我有以下这些函数:

function a(obj)
{
    console.log("function 1 "+obj);
}
function a(x)
{
    console.log("function 2 "+"3");
}
a(1);

为什么总是第二个函数在运行?为什么不是第一个?

不能在同一作用域中有两个函数,且名称相同。第二个将取代第一个。这就是为什么第一个语句永远不会被执行。

如果希望重载函数,可以通过在函数内立即检查实参的类型来实现。例如,考虑以下内容:

function a ( x ) {
    var output;
    switch ( typeof x ) {
        case "string" :
            output = "foo";
            break;
        case "object" :
            output = "bar";
            break;
        default:
            output = typeof x;
    }
    console.log( output );
}

由于第二个函数是在第一个函数之后声明的,因此它将覆盖第一个函数。Javascript不关心参数是否不同,它只按照函数名来处理。