JS不支持重载

xiaoxiao2026-08-28  34

也许你尝试过这样写JS代码: function sayHello(name, message){ alert("Hello! " + name + message); } function sayHello(name){ alert("Hello! " + name); } sayHello("Peter", "Nice to see you."); 可惜你永远也不会得到你想要的结果,这段代码只会返回"Hello! Peter",因为它只会执行第二个function. 测试一下,用函数的length属性可以知道函数需要几个参数: alert(sayHello.length); // 1 证明调用的是function sayHello(name). 也可以直接把函数名引用的函数显示出来: alert(sayHello); 你会看到显示的是第二个函数. 你可以这样写: function sayHello(){ if(arguments.length == 1){ alert("Hello! " + arguments[0]); } if(arguments.length == 2){ alert("Hello! " + arguments[0] + arguments[1]); } } sayHello("Peter"); // "Hello! Peter", sayHello("Peter", ", Nice to see you."); // "Hello! Peter, Nice to see you." arguments是参数数组对象,它存储了传给函数的参数. 原因是function函数只不过是一种引用类型,当你第二次使用函数名定义函数时会把第一次定义的函数覆盖掉. var handle = function(){ alert("Understand?"); } handle(); // "Understand?" 既然函数只是引用类型,那么就可以把它作为参数传给其他函数 var handle = function(){ alert("GoodBye!"); } function say(fun){ fun(); } say(handle); // "GoodBye!" 相关资源:关于JS重载
转载请注明原文地址: https://www.6miu.com/read-5052005.html

最新回复(0)