js的方法重载

这是很简陋的版本,功能距完善还有很长的距离。

<script>
  var obj = {
    values: ['a', 'b', 'c', 'd']
  };

  function addMethod(object, name, fn) {
    var old = object[name];
    if (old === undefined) {
      object[name] = fn;
    } else {
      object[name] = function () {
        if (fn.length == arguments.length) {
          return fn.apply(this, arguments)
        } else {
          return old.apply(this, arguments)
        }
      };
    }
  }
  addMethod(obj, 'find', function () {
    console.log(this)
    return this.values
  });
  addMethod(obj, 'find', function (name) {
    var ret = [];
    for (var i = 0, len = this.values.length; i < len; i++) {
      if (this.values[i].indexOf(name) == 0) {
        ret.push(this.values[i]);
      }
    }
    return ret

  });


console.log(obj.find('a'));
console.log(obj.find());
</script>

运行结果

猜你喜欢

转载自blog.csdn.net/qaqLjj/article/details/88421750