Javascript函数重载,存在呢—还是存在呢?
1.What's is 函数重载?
2.静态语言的重载
#include <iostream>
using namespace std;
void print(int i) {
cout <<"Here is num " << i << endl;
}
void print(string str) {
cout << "Here is string " <<str<< endl;
}
int main() {
print(10);//Here is int 10
print("ten");//Here is string ten
}
function print(i) {
console.log("Here is num"+i);
}
function print(str) {
console.log("Here is string "+str);
}
print(100);//Here is string 100
print("ten");//Here is string ten


3.如何实现具有Javascript特色的函数重载
- Using different names in the first place(使用不同的函数名)
function printNum(num) {
console.log("Here is num "+num);
}
function printString(str) {
console.log("Here is string "+str);
}
printNum(100);//Here is num 100
printString("ten");//Here is string ten
- Using optional arguments like
y = y || 'default'(检测是否提供实参,否则采用默认值)
举例说明,现在我们要同时打印一个数字和一个字符串
function print(num,str){
var inner_num=num||0;
var inner_str=str||"default";
console.log("Here is num "+inner_num);
console.log("Here is string "+inner_str);
}
print();
//Here is num 0
//Here is string default
print(10);
//Here is num 10
//Here is string default
print(10,"ten");
//Here is num 10
//Here is string ten
- Using number of arguments(根据参数数量来实现重载)
function print(num,str){
var len=arguments.length;
if (len===1) {
console.log("Here is num "+num);
}
else if (len===2) {
console.log("Here is num "+num);
console.log("Here is string "+str);
}
else{
console.log("看....,飞碟!");
}
}
print();//看....,飞碟!
print(10);//Here is num 10
print(10,"ten");
//Here is num 10
//Here is string ten
- Checking types of arguments (根据参数类型来实现重载)
function print(num,str){
if (typeof num=="number") {
console.log("Here is num "+num);
}
if (typeof str=="string") {
console.log("Here is string "+str);
}
}
print();//无输出
print(10);//Here is num 10
print('',"ten");//Here is string ten
print(10,"ten");
// Here is num 10
// Here is string ten

function print(num,str){
var len=arguments.length;
if((len===1)&& (typeof arguments[0]==="number")){
console.log("Here is num "+arguments[0]);
}
else if ((len===1)&& (typeof arguments[0]==="string")) {
console.log("Here is string "+arguments[0]);
}
else if((len===2)&& (typeof arguments[0]==="number")&& (typeof arguments[1]==="string")) {
console.log("Here is num "+arguments[0]);
console.log("Here is string "+arguments[1]);
}
else{
console.log("看....,飞碟!");
}
}
print();//看....,飞碟!
print(10);//Here is num 10
print("ten");//Here is string ten
print(10,"ten");
// Here is num 10
// Here is string ten
function foo(a, b, opts) {
}
foo(1, 2, {"method":"add"});
foo(3, 4, {"test":"equals", "bar":"tree"});
function sayName(name){
alert(name);
}
function sum(num1, num2){
return num1 + num2;
}
function sayHi(){
alert("hi");
}
alert(sayName.length); //1
alert(sum.length); //2
alert(sayHi.length); //0
■ 通过其length属性,可以知道声明了多少命名参数
■ 通过arguments.length,可以知道在调用时传入了多少参数
下面介绍一下大牛是如何实现借助这个特性实现函数的重载的
var ninja = {};
addMethod(ninja,'whatever',function(){ /* do something */ });
addMethod(ninja,'whatever',function(a){ /* do something else */ });
addMethod(ninja,'whatever',function(a,b){ /* yet something else */ });
function addMethod(object, name, fn) {
var old = object[name]; //保存原有的函数,因为调用的时候可能不匹配传入的参数个数
object[name] = function() { // 重写了object[name]的方法,是一个匿名函数
// 如果该匿名函数的形参个数和实参个数匹配,就调用该函数
if(fn.length === arguments.length) {
return fn.apply(this, arguments);
// 如果传入的参数不匹配,就调用原有的参数
} else if(typeof old === "function") {
return old.apply(this, arguments);
}
}
}
- 第一个为要绑定方法的对象,
- 第二个为绑定方法所用的属性名称,
- 第三个为需要绑定的方法(一个匿名函数)

//addMethod
function addMethod(object, name, fn) {
var old = object[name];
object[name] = function() {
if(fn.length === arguments.length) {
return fn.apply(this, arguments);
} else if(typeof old === "function") {
return old.apply(this, arguments);
}
}
}
var printer= {};
// 不传参数时,打印“飞碟”
addMethod(printer, "print", function() {
console.log("看,飞碟!");
});
// 传一个参数时,打印数字
addMethod(printer, "print", function(num) {
console.log("Here is num "+num);
});
// 传两个参数时,打印数字和字符串
addMethod(printer, "print", function(num,str) {
console.log("Here is num "+ num);
console.log("Here is string "+str);
});
// 测试:
printer.print(); //看,飞碟!
printer.print(10); //Here is num 10
printer.print(10, "ten");
//Here is num 10
//Here is string ten
// Function.prototype.overload - By 沐浴星光
Function.prototype.overload = function(fn) {
var old= this;
return function() {
if (fn.length===arguments.length) {
return fn.apply(this,arguments);
}else{
return old.apply(this,arguments);
}
}
}
// 不传参数时,打印“飞碟”
function printNone() {
console.log("看,飞碟!");
}
// 传一个参数时,打印数字
function printInt(num) {
console.log("Here is num "+num);
}
// 传两个参数时,打印数字和字符串
function printBoth(num,str) {
console.log("Here is num "+ num);
console.log("Here is string "+str);
}
print=function(){};
print=print.overload(printNone).overload(printInt).overload(printBoth);
print();//看,飞碟!
print(10);//Here is num 10
print(10,"ten");
// Here is num 10
// Here is string ten

Javascript函数重载,存在呢—还是存在呢?的更多相关文章
- javascript 函数重载 overloading
函数重载 https://en.wikipedia.org/wiki/Function_overloading In some programming languages, function over ...
- JavaScript函数重载
译者按: jQuery之父John Resig巧妙地利用了闭包,实现了JavaScript函数重载. 原文: JavaScript Method Overloading 译者: Fundebug 为了 ...
- [转载]浅谈JavaScript函数重载
原文地址:浅谈JavaScript函数重载 作者:ChessZhang 上个星期四下午,接到了网易的视频面试(前端实习生第二轮技术面试).面了一个多小时,自我感觉面试得很糟糕的,因为问到的很多问题都 ...
- javascript arguments与javascript函数重载
1.所 有的函数都有属于自己的一个arguments对象,它包括了函所要调用的参数.他不是一个数组,如果用typeof arguments,返回的是’object’.虽然我们可以用调用数据的方法来调用 ...
- JavaScript “函数重载”
函数重载(function overloading)必须依赖两件事情:判断传入参数数量的能力和判断传入参数类型的能力. JavaScript的每个函数都带有一个仅在这个函数范围内作用的变量argume ...
- 浅谈JavaScript函数重载
上个星期四下午,接到了网易的视频面试(前端实习生第二轮技术面试).面了一个多小时,自我感觉面试得很糟糕的,因为问到的很多问题都很难,根本回答不上来.不过那天晚上,还是很惊喜的接到了HR面电话.现在HR ...
- javascript 函数重载另一种实现办法
最近在读javascript忍者 感受下jquery作者 john Resig对于js的独到见解. 先上代码: function addMethod(object,name,fn){ var old ...
- 理解javascript函数的重载
javascript其实是不支持重载的,这篇文章会和java语言函数的重载对比来加深对javascript函数重载的理解. 以下我会假设读者不了解什么是重载所以会有一些很基础的概念 ...
- JavaScript模拟函数重载
JavaScript是没有函数重载的,但是我们可以通过其他方法来模拟函数重载,如下所示: <!DOCTYPE html> <html> <head> <met ...
随机推荐
- u盘安装系统教程详解
一.准备阶段 提前准备一个至少1G或以上的u盘,方便好用. 1.制作u盘启动工具 (1)工具下载,推荐IT天空的优启通 下载地址:https://www.itiankong.net/thread-37 ...
- java高新技术-java5的静态导入与编译器语法设置
静态导入 import语句可以导入一个类或某个包中的所有类 import static 语句导入有一个类中的某个静态方法或所有静态方法 使用Math.random() 可以这样做 package co ...
- Derivative of the softmax loss function
Back-propagation in a nerual network with a Softmax classifier, which uses the Softmax function: \[\ ...
- BZOJ3331: [BeiJing2013]压力
传送门 Tarjan的三大应用之一:求解点双联通分量. 求解点双联通分量.然后缩点,差分优化即可. //BZOJ 3331 //by Cydiater //2016.10.29 #include &l ...
- 10款最好的 Bootstrap 3.0 免费主题和模板
Twitter Bootstrap 框架已经广为人知,用于加快网站,应用程序或主题的界面开发,并被公认为是迄今对于Web开发的最有实质性帮助的工具之一.在此之前的,各种各样的界面库伴随着高昂的维护成本 ...
- PHP求余函数fmod()
定义和用法 fmod() 函数返回除法的浮点数余数. 语法 fmod(x,y) 参数 描述 x 必需.一个数. y 必需.一个数. 说明 返回被除数(x)除以除数(y)所得的浮点数余数.余数(r)的定 ...
- JavaScript学习总结(二)数组和对象部分
pt学习总结(二)数组和对象部分 2016-09-16 分类:WEB开发.编程开发.首页精华暂无人评论 来源:trigkit4 分享到:更多1 对象部分 Object类型 Object ...
- phpcms专题路径修改
两个文件改三处就可以了,既可以后台点击专题列表链接问题,也可以解决生成专题多一个“/”的问题. 1.\phpcms\modules\special\classes\html.class.php大概第1 ...
- 数据结构快速回顾——平衡二叉树 AVL (转)
平衡二叉树(Balanced Binary Tree)是二叉查找树的一个进化体,也是第一个引入平衡概念的二叉树.1962年,G.M. Adelson-Velsky 和 E.M. Landis发明了这棵 ...
- Linux串口中的超时设置
在Linux下使用串口通信时,默认的阻塞模式是不实用的.而采用select或epoll机制的非阻塞模式,写代码有比较麻烦.幸好Linux的串口自己就带有超时机制. Linux下使用termios.h中 ...