Javascript 嵌套函数与外部函数,带传递事件和参数的箭头函数

Javascript 嵌套函数与外部函数,带传递事件和参数的箭头函数,javascript,Javascript,我了解到,不需要隐私的嵌套函数是反模式的,因为每次都会创建内部函数。因此,我使用requestAnimationFrame和当前时间创建平滑滚动: const smoothScroll = (y, durration, startPos) => { ... const scroll = (currentTime) => { ... if(timeElapsed < durration) return requestAnimatio

我了解到,不需要隐私的嵌套函数是反模式的,因为每次都会创建内部函数。因此,我使用requestAnimationFrame和当前时间创建平滑滚动:

const smoothScroll = (y, durration, startPos) => {
    ...
    const scroll = (currentTime) => {
        ...
        if(timeElapsed < durration) return requestAnimationFrame(scroll);
    }
    requestAnimationFrame(scroll);
}
const smoothScroll=(y、durration、startPos)=>{
...
常量滚动=(当前时间)=>{
...
if(timeappeased
requestAnimationFrame正在传递当前时间,如果将其移到外部,则需要使用箭头函数传递当前时间或创建局部变量:

const smoothScroll = (deg, durration, startPos) => {
    ...
    requestAnimationFrame((currentTime) => {
        scroll(currentTime, deg, durration, startPos) });
}
const scroll = (currentTime, startTime, deg, durration, startPos) => {
    ...
    if(timeElapsed < durration) requestAnimationFrame((currentTime) => {
        rotate(currentTime, deg, durration, startPos) });
}
const smoothScroll=(度、硬度、起始温度)=>{
...
requestAnimationFrame((当前时间)=>{
滚动(当前时间、度、硬度、起始时间)};
}
常数滚动=(当前时间、开始时间、度、硬度、开始时间)=>{
...
如果(时间经过<持续时间)requestAnimationFrame((当前时间)=>{
旋转(当前时间、度、硬度、起始时间)};
}
那么,在当前的引擎优化中,这仍然被认为是反模式的吗?如果我不需要封装,我应该使用带有paramaters one的arrow函数吗

我读到当不需要隐私时嵌套功能是反模式的

好的,当它不是必需的1时,它可能是一个反模式嵌套函数,但在您的情况下,它是必需的,因为对局部变量的闭包访问。所以保持原样,没什么问题


1:保持局部变量私有是一回事。代码结构可能是另一种。您必须根据性能来评估这一点-创建函数很便宜,因此除非它实际上成为瓶颈,否则嵌套没有问题。

第二种方法是优先考虑的,因为您现在既有通用的
滚动操作,也有
平滑滚动操作-如前所述,您不会每次调用
smoothScroll
时都重新创建
scroll
操作。@lux错误。第一种方法实际上效率更高,因为它只创建一次
scroll
函数,然后在所有
requestAnimationFrame
调用中重用它。第二个代码段将在每个动画帧上重新创建
(currentTime)=>{…}
匿名函数。@Bergi错了。在第一种情况下,在每次调用
smoothScroll
时,scroll都会被创建并分配给
scroll
,并且还提供了一个好处,即不会将消费者锁定为仅使用一个滚动浏览器的实现。@lux我不是说
scroll
,我说的是在一次调用
smoothScroll
期间额外的箭头函数-请注意动画的递归。而且没有“锁定”,滚动
scroll
函数只是
smoothScroll
的一个实现细节,您几乎不想直接调用它。如果您找到了重用部分代码(
位)的理由,您仍然可以通过引入辅助函数进行重构。