//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 people = { values: ["Dean Edwards", "Alex Russell", "Dean Tom"] }; /* 下面开始通过addMethod来实现对people.find方法的重载 */ // 不传参数时,返回peopld.values里面的所有元素 addMethod(people, "find", function() { return this.values; }); // 传一个参数时,按first-name的匹配进行返回 addMethod(people, "find", function(firstName) { var ret = []; for(var i = 0; i < this.values.length; i++) { if(this.values[i].indexOf(firstName) === 0) { ret.push(this.values[i]); } } return ret; }); // 传两个参数时,返回first-name和last-name都匹配的元素 addMethod(people, "find", function(firstName, lastName) { var ret = []; for(var i = 0; i < this.values.length; i++) { if(this.values[i] === (firstName + " " + lastName)) { ret.push(this.values[i]); } } return ret; }); // 测试: console.log(people.find()); //["Dean Edwards", "Alex Russell", "Dean Tom"] console.log(people.find("Dean")); //["Dean Edwards", "Dean Tom"] console.log(people.find("Dean Edwards")); //["Dean Edwards"]
好啦,实现JS函数重载就写这么多啦,如果亲们有更好的实现方法,欢迎评论交流哈~
感兴趣的朋友可以使用在线HTML/CSS/JavaScript代码运行工具:测试上述代码运行效果。
更多关于JavaScript相关内容感兴趣的读者可查看本站专题:《javascript面向对象入门教程》、《JavaScript错误与调试技巧总结》、《JavaScript数据结构与算法技巧总结》、《JavaScript遍历算法与技巧总结》及《JavaScript数学运算用法总结》