请教下,下面 写法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
写法2相当于做了一个错误检测的外壳。当其他方法想要检测的时候也可以重复使用,而不是对原方法重新改造。