JavaScript中没有重载(...)

64 阅读1分钟

重载概念:函数名相同,参数不同(同名不同参)

思考如果要实现重载如何做?

下面代码参考:juejin.cn/post/684490…

function addMethod (obj, name, fn) {  var old = obj[name];  obj[name] = function () {      console.log(1) //打印1      //函数形参的个数(fn.length)是否等于实参的个数(arguments.length)      if(fn.length === arguments.length){          console.log(2) // 打印2          return fn.apply(this,arguments);      }else if(typeof old === 'function'){          console.log(3) // 打印3          return old.apply(this,arguments);      }  }}var p = {useName: 'syu'}addMethod(p, "show", function() {  console.log(this.useName + '-->' + 'show1')})addMethod(p, "show", function(str) {  console.log(this.useName + '-->' + str)})addMethod(p, "show", function(str, str2) {  console.log(this.useName + '-->' + str + str2)})p.show();p.show('a1');p.show('a1', 'a2')

函数的length属性:表示函数形参的个数

eg:

例子1var a = function(){
    console.log("arguments.length:", arguments.length);//1
    //arguments表示函数的实参
}
a('实参');
console.log(a.length);// 0 函数.length便是函数的形参的个数

例子2function test(a, b) {}
test.length;//2