Fred J. Fred J. - 1 month ago 12
Javascript Question

Print function name private method of IIFE

This Meteor sever code has

printFuncName
as a private method to a IIFE. When it is called from a public method, it gives the error:


TypeError: Cannot read property 'name' of null


Why is it doing this and How can it be fixed so that it prints the function name where is is called from? Thanks



funcObj = (function() {

const printFuncName = (str) => {
const info = str ? ' ' + str + ' ' : ' ';
console.log(arguments.callee.caller.name + info); //<---- Error line
};

return {
myPub: () => {
printFunctionName('info');
}

}

}());

Answer

Assuming you want to access the caller of printFuncName, the problem is that it's an arrow function, and therefore has no arguments binding. You are accessing the arguments of the IIFE.

Anyways, you should never use arguments.callee. It's not standard and you can just reference the function:

(function() {
  const printFuncName = (str) => {
    const info = str ? ' ' + str + ' ' : ' ';
    console.log(printFuncName.caller.name + info); // "myPub info " (maybe)
  };
  return {
    myPub() {
      printFuncName('info');
    }
  }
}()).myPub();

Be aware caller is also not standard. You should not use this. Do not rely on it. It will throw in strict mode. May not work in sloppy mode.

Comments