0

When I define an object I can reach all its properties by using the dot character and the same applies to built-in functions like String, Array, Math, etc. But I cannot loop through them by using for(# in # for example. It says String is native code but still I can reach all its members albeit I cannot iterate through them. I know window is iterable but their 'sub-functions' appear to be not. Why is that? Is there a chance to call the properties without explicitly typing their names in? Can I list all its members somehow?

I am aware of that It does not look useful and no one would need it in production. I am asking it because I could not do it and I hope someone can give me some help.

1
  • How would you call a member function without knowing its name ? That's king of stupid. If you want to call a function when you only have a String (representing the function's name), juste do object[str](); Commented Aug 7, 2014 at 9:40

1 Answer 1

1

You can get all names only of own(!!!) properties

Object.getOwnPropertyNames(YOUR_OBJECT)

It means, this method doesn't enumerate inherited properties. And if you want to enumerate inherited properties you can use YOUR_OBJECT.__proto__, but it works only in Mozilla

Sign up to request clarification or add additional context in comments.

6 Comments

@Bergi How would you get a list of the prototypes with this method?
for (var prototypes=[], p=YOUR_OBJECt; p=Object.getPrototypeOf(p); prototypes.push(p)); should do it. No difference in functionality to getting __proto__, except for being standard.
@Bergi but you have to stop youe loop when p will equal Object, because Object.getPrototypeOf(Object) == function() {} and you have infinite loop
No, you've got something wrong there. Object -> Function.prototype -> Object.prototype -> null. Prototype chains are guaranteed to have no circles, so this cannot be an infinite loop.
@Bálint Juhász getPrototypeOf returns only prototypes, and after that you have to call getOwnPropertyNames() for every prototype.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.