传播语法 ecmascript



我以前使用过扩展语法,但不是这样。我对(...fns)(...args)之间的跳跃感到困惑.我知道fns是传入的函数(内部OnLoad和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)

提前谢谢你

其余参数语法将所有参数收集到一个数组中。在这种情况下,部分应用程序用于存储函数数组(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);

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

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

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

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

最新更新