Get code of methods during iteration on an object

I know that in javascript I can iterate over an object to get all its properties. If one or more properties is a method, can you see what code is in the method, and not just the name of the method? For instance.

var a = someobject; for (property in a) { console.log(property); } 

Is it possible to get the method code in the same way? Thank you in advance.

+4
source share
4 answers

Yes. It really works. Try:

 var a = {}; a.id = 'aaa'; a.fun = function(){alert('aaa');} for (x in a) { var current = a[x].toString(); if(current.indexOf('function') == 0){ current = current.substring(current.indexOf('{')+ 1, current.lastIndexOf('}')); } console.log(current); } 

But it will not work for native browser code.

+2
source

You need to use toString , per standard . i.e:

 //EX: var a = {method:function(x) { return x; }}; //gets the properties for (x in a) { console.log(a[x].toString()); } 

You can also use toSource , but this is NOT part of the standard.

PS: trying to reliably iterate an object using for : loop is non-trivial and dangerous ( for..in only iterates over the [[Enumerable]] properties, for one), try to avoid such constructions. I would ask why you are doing this?

+2
source

You can use toString method for function

i.e.

 function hello() { var hi = "hello world"; alert(hi); } alert(hello.toString());​ 

Update: the reason it didn't work in JSFiddle was because I forgot to add the result inside console.log or alert - http://jsfiddle.net/pbojinov/mYqrY/

+1
source

As long as a is an object, you should be able to use square notation and request the value from an argument with the same name as the property of the objects. For instance:

 a[ property ]; 

If you write typeof( property ) , it will return "string" what we want.

0
source

All Articles