2

This code iterates over just the enumerable properties of an object:

for (variable in object)
      statement

The following code iterates over all properties not just the enumerable ones:

function getAllPropertyNames(obj) {
  var result = [];
   while (obj) {
       Array.prototype.push.apply(result, Object.getOwnPropertyNames(obj));
       obj = Object.getPrototypeOf(obj);
   }
    return result;
}
  1. When does the loop while (obj) break?

  2. How do lines within the while block work to add the own property names of obj to result?

chefcurry7
  • 2,763
  • 6
  • 22
  • 29
  • 1
    1. When `Object.getPrototypeOf(obj)` returns `null`. 2. `Array.prototype.push.apply(result, Object.getOwnPropertyNames(obj));` is the same as `var tmp = Object.getOwnPropertyNames(obj); result.push(tmp[0], tmp[1], ...)`. Learn more about `.apply` from MDN: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/apply. See also http://stackoverflow.com/q/1986896/218196 – Felix Kling Aug 19 '15 at 05:01
  • Why is Object.getPrototypeOf(obj) needed ? – chefcurry7 Aug 19 '15 at 05:08
  • @chefcurry7—so the OP can collect inherited properties too. – RobG Aug 19 '15 at 05:17
  • To clarify Felix's comments (which should be an answer), the `[[Prototype]]` of *Object.prototype* is null (see [*ECMAScript ed 6 §9.1*](http://www.ecma-international.org/ecma-262/6.0/index.html#sec-ordinary-object-internal-methods-and-internal-slots)), which is the end of all built–in prototype chains. This isn't guaranteed to work with host objects, though for implementations consistent with the current standard, it probably will. – RobG Aug 19 '15 at 05:21
  • Oh, I see that ECMAScript ed 6 doesn't have host objects any more, it has [*exotic objects*](http://www.ecma-international.org/ecma-262/6.0/index.html#sec-exotic-object) defined by the non sequitur: *object that does not have the default behaviour for one or more of the essential internal methods that must be supported by all objects*. If something **must** be supported by **all objects**,how can some be allowed to not support it? Perhaps it should read: "*…by all built–in objects*". – RobG Aug 19 '15 at 05:34

1 Answers1

0
  1. When does the loop while (obj) break?

When there are no more prototypes in the prototype chain getPrototypeOf returns null. For regular objects, this happens when you try to get the prototype of Object.prototype.

  1. How do lines within the while block work to add the own property names of obj to result?

Array.prototype.push.apply(result, array) passes each element in the array as argument to result.push. It is like calling result.push(a[0], a[1], ...) where a is Object.getOwnPropertyNames(obj).

Rodrigo5244
  • 3,896
  • 1
  • 21
  • 33