Object.keys(someobject)
我很乐意这样做我知道Object是Object构造函数,而keys()是它的一个方法,key()将返回一个列表,作为第一个参数给出的任何对象.我的问题不是如何得到一个对象的键 – 请不要回答与解答这个的非答案.
我的问题是,为什么没有更可预测的键()或getKeys()方法,或者键实例变量在Object.prototype上可用,所以我可以有:
someobject.keys()
或作为实例变量:
someobject.keys
并返回数组的键?
再次,我的意图是了解Javascript的设计,以及采用一些不直观的提取键机制的目的是什么.我不需要帮助获得钥匙.
解决方法
我最近读了这个,但是现在找不到来源.可以理解的是,在许多情况下,您必须使用Object.prototype.keys.call(myobject),因为myobject.keys的可能性已经在对象中被用于其他的东西.
我想你会发现这个archived mail thread有趣的,例如Brendan Eich在ECMAScript 5中讨论了新方法的一些方面.
更新:
在mail-archive挖掘我发现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.