调用并返回一个函数

时间:2019-01-13 07:33:17

标签: javascript function

在JS中是否可以做到这一点

function namedFunction(elements,args) {
  const domElements = document.querySelector(elements); 
  const initialValue = 0;
  let incrementBy = 5; 

  return function() {
    // Do something to domElements based on initialValue and incrementBy
    // function needs to run the first time namedFunction is called
    // and this is the only function that needs to run on subsequent calls to namedFunction
   }.call(null)
   // the .call does not work as intended here, but this is basically what I want to do.
}

我想我可以对上面的代码执行namedFunction()()来调用它们,但是我想知道是否还有另一种方法。

该函数的较长版本如下所示:

function namedFunction(elements,args) {
  const domElements = document.querySelector(elements); 
  const initialValue = 0;
  let incrementBy = 5; 

  function namedFunctionEventHandler() {
    // Do something to domElements based on initialValue and incrementBy
    // function needs to run the first time namedFunction is called
    // and this is the only function that needs to run on subsequent calls to namedFunction
  }

  namedFunctionEventHandler(); 
  return namedFunctionEventHandler; 
}

目标是传递一个函数作为事件处理程序,该函数在第一次运行时会进行初始计算,缓存dom元素和更重的内容,然后执行在返回的函数中抽象的逻辑随后的调用将使用闭包中的数据。

编辑:namedFunction不需要接受任何参数,仅用于演示目的。

document.addEventListener('scroll', namedFunction)

是我想要做的。

@CertainPerformance-对不起,我看错了你的答案。 如果您看一下我想要获得的最终结果,您的建议实际上不会按预期工作,就像我将调用的函数作为事件处理程序传递一样,它将在事件实际发生之前运行。

2 个答案:

答案 0 :(得分:0)

您可以将namedFunction设置为IIFE,以保存对函数的引用(最初未定义)。在调用时,如果未定义该变量,请执行昂贵的计算,然后将其分配给该变量;如果定义了变量 ,则只需调用它即可。

const handler = (() => {
  let cheapFn;
  return () => {
    if (cheapFn) {
      cheapFn();
      return;
    }
    // expensive calculations here
    const domElements = document.querySelector(elements); 
    ...
    cheapFn = () => {
      // assign to cheapFn
    };
    cheapFn();
  };
})();

演示:

const handler = (() => {
  let cheapFn;
  return () => {
    if (cheapFn) {
      cheapFn();
      return;
    }
    // expensive calculations here
    console.log('expensive');
    cheapFn = () => {
      console.log('cheap');
    };
    cheapFn();
  };
})();
document.addEventListener('scroll', handler);
body {
  height: 400px;
}
body

答案 1 :(得分:0)

您可以利用JavaScript中的函数是一类对象这一事实,并将函数状态(已初始化/未初始化)存储在该函数的属性中。

初始化期间计算出的数据也可以存储在函数属性中,请看一下演示:

const namedFunction = function(elements,args) {
  if (!namedFunction.isInitialized) {
      console.log('Initialization: Computing initial value...');
      namedFunction.initialValue = 10 * 10;
      console.log(`Initial value: ${namedFunction.initialValue}`);
      namedFunction.isInitialized = true;
  }
  return function() {
      console.log('Running regular operation:');
      console.log(`Current value: ${--namedFunction.initialValue}`);
  }.call(null)
}

document.getElementById('demo').addEventListener('click', namedFunction);
<button id="demo">Run</button>