Search code examples
javascriptarraysooplanguage-designjavascript-objects

Javascript: why Object.keys(someobject), rather than someobject.keys?


I frequently get an array of an objects keys using:

Object.keys(someobject)

I'm comfortable doing this. I understand that Object is the Object constructor function, and keys() is a method of it, and that keys() will return a list of keys on whatever object is given as the first parameter. My question is not how to get the keys of an object - please do not reply with non-answers explaining this.

My question is, why isn't there a more predictable keys() or getKeys() method, or keys instance variable available on Object.prototype, so I can have:

someobject.keys()

or as an instance variable:

someobject.keys

And return the array of keys?

Again, my intention is to understand the design of Javascript, and what purpose the somewhat unintuitive mechanism of fetching keys serves. I don't need help getting keys.


Solution

  • I guess an answer to your question is "Because the committee decided so", but I can already hear you ask "why?" before the end of this sentence.

    I read about this recently but I can't find the source right now. What it boiled down to was that in many cases you had to use Object.prototype.keys.call(myobject) anyway, because the likelihood of myobject.keys already being used in the object for something else.

    I think you will find this archived mail thread interesting, where for example Brendan Eich discuss some aspects of the new methods in ECMAScript 5.

    Update: While digging in the mail-archive I found this:

    Topic: Should Object.keys be repositioned as Object.prototype.keys

    Discussion: Allen argued that this isn't really a meta layer operation as it is intended for use in application layer code as an alternative to for..in for getting a list of enumerable property names. As a application layer method it belongs on Object.prototype rather than on the Object constructor. There was general agreement in principle, but it was pragmatically argued by Doug and Mark that it is too likely that a user defined object would define its own property named "keys" which would shadow Object.prototype.keys making it inaccessible for use on such objects.

    Action: Leave it as Object.keys.