简体   繁体   English

测试在哪个函数中执行回调

[英]Test in which function a callback is executed

I'm trying to test in which function this callback function in executed. 我正在尝试测试此回调函数在哪个函数中执行。 It should return a boolean value. 它应该返回一个布尔值。 I hope you know what I mean. 我希望你明白我的意思。

Here the code example: 这里的代码示例:

function test(par, callback) {
  // ...
  if (typeof callback == 'function') { // make sure the callback is a function
    callback.call(this);
  }

}

test("par", function() {
  console.log("Test if in function test: " + "<if this is in function test>");
});

Is this similar to instanceof ? 这类似于instanceof吗?

There's a non-standard way of doing it since the removal of arguments.caller 自删除arguments.caller以来,存在一种非标准的方法。

 function test(par, callback) { // ... if (typeof callback == 'function') { // make sure the callback is a function callback.call(this); } } test("par", function cb() { var isTestCaller = cb.caller === test; console.log("Test if in function test: " + isTestCaller); }); 

Another possible way doing it through error stacks (still non-standard): 通过错误堆栈(仍然是非标准的)执行此操作的另一种可能方法:

 var checkCaller = function(fnName) { var e = new Error(); var caller = e.stack.split('\\n')[2].trim().split(' ')[1]; return caller === fnName; } function wrapper(){ console.log(checkCaller('wrapper')); } wrapper(); 

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

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