0

I can use a variety of means to iterate over properties of objects that I've created in JavaScript, e.g.

Object.keys({one: 1, two: 2, three: function() {return 2+1}})
> ["one", "two", "three"]

I am looking for a way to do the same thing, but with built-in objects, like Object, String, Array. I'd like to call something like this:

Object.keys(String)

... and get this output:

> ["length", "fromCharCode", "fromCodePoint", "prototype", etc.]

... where etc. is the list of properties/methods of the String built-in object.

So far I've tried the following, with no luck:

Object.keys(String)
Object.keys(String())
Object.keys(String.prototype)
Object.keys(String.__proto__)
Object.keys(new String())
for (i in String) {...}

They all return an empty array ([]).

antun
  • 2,038
  • 2
  • 22
  • 34
  • `Object.keys(String.prototype)` returns an array of 4 keys for me – Taplar Oct 20 '20 at 21:41
  • 4
    Are you looking for [`Object.getOwnPropertyNames`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/getOwnPropertyNames) probably coupled with [`Object.getPrototypeOf`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/getPrototypeOf)? There is also [`Object.getOwnPropertyDescriptors`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/getOwnPropertyDescriptors) for even more property information. – VLAZ Oct 20 '20 at 21:43
  • 2
    See this nice answer: https://stackoverflow.com/a/55006988/2170192 – Alex Shesterov Oct 20 '20 at 21:46
  • @Taplar I see that it does for me in Safari, but not in Chrome. (I get `["formatUnicorn", "truncate", "splitOnLast", "contains"]`). But I'm looking to get all of the available methods. – antun Oct 20 '20 at 21:46
  • @AlexShesterov aah. That is exactly what I was looking for. I spent ages searching for an answer before posting, I don't know how I didn't find that. – antun Oct 20 '20 at 21:48
  • 1
    no worries. the keywords here are "non-enumerable" and "inherited" properties. – Alex Shesterov Oct 20 '20 at 22:29
  • @AlexShesterov I see now. I was searching for terms like "built-in" and "native objects", but the issue is really not about the objects, but about their properties. I found this page which explains how properties are exposed, and to which methods, in JS: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Enumerability_and_ownership_of_properties – antun Oct 21 '20 at 16:13

0 Answers0