请教下这种包裹写法有什么好处

新手上路,请多包涵

请教下,下面 写法2和写法1相比有什么好处?

写法1:

function invoke(obj, method, args) {
  try {
    return obj[method].apply(this, args);
  } catch (e) {
    captureError(e); // report the error
    throw e; // re-throw the error
  }
}

invoke(Math, 'highest', [1, 2]); // throws error, no method Math.highest

写法2:

function wrapErrors(fn) {
  if (!fn.__wrapped__) {
    fn.__wrapped__ = function () {
      try {
        return fn.apply(this, arguments);
      } catch (e) {
        captureError(e); // report the error
        throw e; // re-throw the error
      }
    };
  }

  return fn.__wrapped__;
}

var invoke = wrapErrors(function(obj, method, args) {
  return obj[method].apply(this, args);
});

invoke(Math, 'highest', [1, 2]); // no method Math.highest
阅读 1.9k
2 个回答

写法2相当于做了一个错误检测的外壳。当其他方法想要检测的时候也可以重复使用,而不是对原方法重新改造。

这是装饰器模式,可以在不改变原有类的情况下增强功能

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题