简体   繁体   中英

Get code of methods while iterating over object

I know in javascript I can iterate over an object to get all of it's properties. If one or more of the properties is a method, is it possible to see what code is in the method instead of just the method name? Eg

var a = someobject;

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

Is it possible to get method code in a way similar to this? Thank you in advance.

Yes. It actually 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 browser native code.

You need to use toString , per the standard . ie:

//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 it is NOT part of the standard.

PS: attempting to reliably iterate through an object with a for : loop is nontrivial and dangerous ( for..in only iterates over [[Enumerable]] properties, for one), try to avoid such constructs. I would ask why, exactly, are you doing this?

You can use the toString method on the function

ie

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

alert(hello.toString());​

Update: The reason it wasn't working in JSFiddle was because I forgot to add the output inside of either console.log or alert - http://jsfiddle.net/pbojinov/mYqrY/

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

a[ property ];

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM