May 28, 2009

what’s that function?

JavaScript lack the ability to reflect a method’s bound property name to the method’s function itself. I figured out a simple way around this:

function whoAmI(fn, that){
  for(var i in that){ 
   if(that[i]===fn){ 
      return i; 
   }
  }
} // end whoAmI()

this.fred = function john(){
  var myName = whoAmI(arguments.callee, this);
return myName;
}

fred()//==="fred"
this could be helpful to create re-usable or overloading functions that use the function’s calling context as an input in their decision structure. it can also snoop for a functions existance as a method on any object, by passing that object as the second argument. if found, you get the property name of the methods, otherwise it returns undefined.