get function name in strict mode  [ 691 views ]

Goal: show the name of the called function in strict mode

If I want to see the function name I can put it like this

'use strict';
var myFunction(){
  ...
  console.log('myFunction called');
  ...
}

but I like the globalized solutions and don’t forget the strict mode, where the possibilities are restricted.
There is nothing else to do just throw an exception and read from the error stack like this:

'use strict';
var myFunction(){
  ...
  try {
    throw new Error();
  }
  catch (e) {
    console.log('Function called:', e.stack.split('at ')[1].split(' ')[0].split('.').last());
  }
  ...
}

in globalized version

'use strict';
var showMyName(){
  try {
    throw new Error();
  }
  catch (e) {
    console.log('Function called:', e.stack.split('at ')[2].split(' ')[0].split('.').last());
  }
};

var myFunction(){
  ...
  showMyName();
  ...
}

Be careful in the second version the last called function is the showMyName() itself that is why we need the previous one from the stack 🙂

One more thing: the end of the long split row … e.stack.split('at ')[2].split(' ')[0].split('.').last()
the split() result is an array and we need the last element – so the last() is an Array object extend like this

Array.prototype.last=function(){
  return this[this.length - 1];
};

so the picture is complete now.

#sidebar a { color:#fff; } #sidebar ul ul li { color: #DEF585; } #sidebar h2 { color: #fff; } #sidebar ul p, #sidebar ul select { color: #BEDDBE; } #backfly { background: url(images/golfBallWallPaper.jpg) left bottom fixed repeat-x #65a51d; }