简体   繁体   中英

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 ?

There's a non-standard way of doing it since the removal of 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(); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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