Tuesday 24 April 2012

Simple Reflection in Javascript


I learned something cool today, for those who are into Reflection in other languages...

function abc(){
  console.log('hello');
}

var obj = { 
  method: abc
};


//1
abc.toString() === 'function abc(){console.log(\'hello\');}';

//2
obj.method.toString() === 'function abc(){console.log(\'hello\');}';


The result from toString() on a function is, however, implementation-specific. Firefox, for instance, returns a 'compiled' version of a function, thus

function add(){

  return 2+3;

}



add.toString() === 'function add(){return 5;}';   //in Firefox

add.toString() === 'function add(){return 2+3;}'; //in node.js





Regardless, I like the fact that as in //2 above, I can inspect the name of the function that has been assigned to my object's method.  I'll post more concrete examples if/when I use it for real :)