简体   繁体   English

我如何知道 function 是否已被调用?

[英]How can I know if a function has been called or not?

I'm making a small reusable module for my use.我正在制作一个可重复使用的小模块供我使用。 and stopped on a point in my code which is, how can I make sure that the consumer of my module has called a function I provided to him or not in one of the methods of my module?并停在我的代码中的一个点上,即,我如何确保我的模块的使用者调用了我提供给他的 function,或者我的模块的一个方法中没有调用?

Basically, the API of the module looks like the forEach method, where my module passes internally arguments just like how forEach works基本上,模块的 API 看起来像 forEach 方法,我的模块在内部传递 arguments 就像 forEach 的工作方式一样

myModule.myMethod(callbackFunc, z)

myModule internally calls your callbackFunc with the following arguments: anotherFunc , x , y myModule内部使用以下 arguments 调用您的callbackFuncanotherFuncxy

Example usage:用法示例:

myModule.myMethod((anotherFunc, x, y) => {
    if (x == true) anotherFunc()
}, z)

How can I know that the consumer of the myMethod has called passed_function or not?我怎么知道myMethod的消费者是否调用passed_function

Assuming anotherFunc is something you create internally, you can write it so that it updates a boolean, and then later you can check that boolean. For example:假设anotherFunc是您在内部创建的东西,您可以编写它以更新 boolean,然后您可以检查 boolean。例如:

function myMethod(callback, z) {
  let hasBeenCalled = false;
  const anotherFunc = () => {
    hasBeenCalled = true;
    // ...
  }

  callback(anotherFunc, 'hello', 'world');

  if (hasBeenCalled) {
    console.log('they called it!');
  }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM