Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>For production code requiring a large compatibility with client browsers I still suggest Ivan Nevostruev's answer above with shim to ensure <code>Object.keys</code> in older browsers. However, it's possible to get the exact functionality requested using ECMA's new <code>defineProperty</code> feature.</p> <p><strong>As of ECMAScript 5 - Object.defineProperty</strong></p> <p>As of ECMA5 you can use <a href="https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Object/defineProperty" rel="nofollow noreferrer"><code>Object.defineProperty()</code></a> to define non-enumerable properties. The <a href="http://kangax.github.io/compat-table/es5/#test-Object.defineProperty" rel="nofollow noreferrer"><strong>current compatibility</strong></a> still has much to be desired, but this should eventually become usable in all browsers. (Specifically note the current incompatibility with IE8!)</p> <pre><code>Object.defineProperty(Object.prototype, 'keys', { value: function keys() { var keys = []; for(var i in this) if (this.hasOwnProperty(i)) { keys.push(i); } return keys; }, enumerable: false }); var o = { 'a': 1, 'b': 2 } for (var k in o) { console.log(k, o[k]) } console.log(o.keys()) # OUTPUT # &gt; a 1 # &gt; b 2 # &gt; ["a", "b"] </code></pre> <p>However, since ECMA5 already added <code>Object.keys</code> you might as well use:</p> <pre><code>Object.defineProperty(Object.prototype, 'keys', { value: function keys() { return Object.keys(this); }, enumerable: false }); </code></pre> <p><strong>Original answer</strong></p> <pre><code>Object.prototype.keys = function () { var keys = []; for(var i in this) if (this.hasOwnProperty(i)) { keys.push(i); } return keys; } </code></pre> <hr> <p><strong>Edit:</strong> Since this answer has been around for a while I'll leave the above untouched. Anyone reading this should also read Ivan Nevostruev's answer below.</p> <p>There's no way of making prototype functions non-enumerable which leads to them always turning up in for-in loops that don't use <code>hasOwnProperty</code>. I still think this answer would be ideal if extending the prototype of Object wasn't so messy.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload