当前位置:Gxlcms > JavaScript > JavaScript的函数重载详解

JavaScript的函数重载详解

时间:2021-07-01 10:21:17 帮助过:2人阅读

这次给大家带来JavaScript的函数重载详解,JavaScript的函数重载的注意事项有哪些,下面就是实战案例,一起来看一下。

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);
    };
}// 不传参数时,返回所有namefunction find0(){      return this.names;
}// 传一个参数时,返回firstName匹配的namefunction 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都匹配的namefunction 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

相信看了本文案例你已经掌握了方法,更多精彩请关注Gxl网其它相关文章!

相关阅读:

CSS中的margin负值如何使用

一份好用的jquery的表单验证插件

js声明函数的四种方式

以上就是JavaScript的函数重载详解的详细内容,更多请关注Gxl网其它相关文章!

人气教程排行