传播语法ecmascript

时间:2018-07-18 13:43:36

标签: reactjs ecmascript-6

我以前使用过传播语法,但不是这样。我对(...fns)(...args)之间的跳跃感到困惑。我知道fns是传入的函数(internalOnLoad和onLoad),args是属于相应函数的参数。但是,当每个函数将其参数传递给函数(... args)=> fns.forEach(...)时,会是什么样?

const callAll = (...fns) => (...args) => fns.forEach(fn => fn && fn(...args));

const internalOnLoad = () => console.log("loaded");

const Avatar = ({ className, style, onLoad, ...props }) => (
  <img 
    className={`avatar ${className}`}
    style={{ borderRadius: "50%", ...style }}
    onLoad={callAll(internalOnLoad, onLoad)}
    {...props} 
  />
);

Avatar.propTypes = {
  src: PropTypes.string.isRequired,
  alt: PropTypes.string.isRequired,
  className: PropTypes.string,
  style: PropTypes.object,
  onLoad: PropTypes.func
};

您能给我一个直观的外观描述吗?例如。像这样调用callAll = (...fns)callAll(internalOnLoad, onLoad)与callAll相同,将收到类似callAll = (internalOnLoad, onLoad)

的参数

提前谢谢

2 个答案:

答案 0 :(得分:3)

rest parameters syntax将所有参数收集到一个数组中。在这种情况下,partial application用于存储函数数组(fns),并返回一个新函数。调用新函数时,它将调用fns中的函数,并将参数(args)传递给每个函数。

如果我们使用标准的JS函数,它将是:

function callAll(...fns) { 
    return (...args) {
        fns.forEach(fn => fn && fn(...args));
    }
}

示例:

const callAll = (...fns) => (...args) => fns.forEach(fn => fn && fn(...args));

const callFns = callAll (
  (a, b) => console.log(a + b + 10),
  (a, b) => console.log(a + b + 20),
  (a, b) => console.log(a + b + 30),
);

console.log(callFns); // you can see the function that was returned in the console.

callFns(1, 2);

答案 1 :(得分:0)

const callAll = (...fns) => (...args) => fns.forEach(fn => fn && fn(...args));

第一个...获得所有功能。

第二个...获取所有参数。

第三个...将带有fn.apply(undefined, args)的参数而不是fn(args)插入到函数中。

相关问题