关于underscore中_.invoke的小疑问


underscore1.3.3 的_.invoke 这个function是这样的:


 _.invoke = function(obj, method) {
    var args = slice.call(arguments, 2);
    return _.map(obj, function(value) {
      return (_.isFunction(method) ? method || value : value[method]).apply(value, args);
    });
  };

请问下面这句代码中为什么三元运算符中要加个逻辑或的判断,有什么作用呢?是出于什么样的考虑?我去掉后好像也没发现什么错误。


 return (_.isFunction(method) ? method || value : value[method]).apply(value, args);

underscore 前端 web前端开发 JavaScript

GGRR297 9 years, 6 months ago

underscore写错了吧,这个或一点用也没有,还有可能出现value[method]不是函数的问题。所以新的underscore已经修改了这个方法的实现:


 _.invoke = restArgs(function(obj, method, args) {
    var isFunc = _.isFunction(method);
    return _.map(obj, function(value) {
        var func = isFunc ? method : value[method];
        return func == null ? func : func.apply(value, args);
    });
});

这样好多了。

风吹屁屁凉 answered 9 years, 6 months ago

Your Answer