JavaScript函数重载

转载自:作者Fundebug以及本文地址:https://blog.fundebug.com/2017/07/24/javascript_metho_overloading/

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);
    };
}
// 不传参数时,返回所有name
function find0()
{  
    return this.names;
}
// 传一个参数时,返回firstName匹配的name
function find1(firstName)
{  
    var result = [];  
    for (var i = 0; i < this.names.length; i++)
    {    
        if (this.names[i].indexOf(firstName) === 0)
        {      
            result.push(this.names[i]);    
        }  
    }  
    return result;
}
// 传两个参数时,返回firstName和lastName都匹配的name
function find2(firstName, lastName)
{ 
    var result = [];  
    for (var i = 0; i < this.names.length; i++)
    {    
        if (this.names[i] === (firstName + " " + lastName))
        {      
            result.push(this.names[i]);    
        }  
    }  
    return result;
}
function Users()
{
    addMethod(Users.prototype, "find", find0);
    addMethod(Users.prototype, "find", find1);
    addMethod(Users.prototype, "find", find2);
}
var users = new Users();
users.names = ["John Resig", "John Russell", "Dean Tom"];
console.log(users.find()); // 输出[ 'John Resig', 'John Russell', 'Dean Tom' ]
console.log(users.find("John")); // 输出[ 'John Resig', 'John Russell' ]
console.log(users.find("John", "Resig")); // 输出[ 'John Resig' ]
console.log(users.find("John", "E", "Resig")); // 输出undefined
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容