首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >扩展语法ecmascript

扩展语法ecmascript
EN

Stack Overflow用户
提问于 2018-07-18 21:43:36
回答 2查看 181关注 0票数 4

我以前使用过扩展语法,但不是以这种方式。我对从(...fns)(...args)的跳转感到困惑。我知道fns是传入的函数(internalOnLoad和onLoad),args是属于相应函数的参数。但是当每个函数都将它们的参数传递给函数(...args) => fns.forEach(...)时会是什么样子呢?

代码语言:javascript
复制
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)参数

提前谢谢你

EN

回答 2

Stack Overflow用户

发布于 2018-07-18 21:49:18

在本例中,partial application用于存储函数数组(fns),并返回一个新函数。当新函数被调用时,它将调用fns中的函数,并将参数(args)传递给每个函数。

代码语言:javascript
复制
function callAll(...fns) { 
    return (...args) {
        fns.forEach(fn => fn && fn(...args));
    }
}

示例:

代码语言:javascript
复制
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);

票数 3
EN

Stack Overflow用户

发布于 2018-07-18 21:55:20

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

第一个...获取所有函数。

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

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

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/51403615

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档