If not for-in then what?

Andrea Giammarchi andrea.giammarchi at gmail.com
Wed Mar 28 08:40:53 PDT 2012


actually, to be consistent with Array.prototype.forEach, descriptor should
be the first argument ... apologies

On Wed, Mar 28, 2012 at 5:39 PM, Andrea Giammarchi <
andrea.giammarchi at gmail.com> wrote:

> I'd love to see this implemented natively ...
>
> (function (Object) {
>   var
>     forEach = "forEach",
>     ObjectPrototype = Object.prototype
>     getOwnPropertyNames = Object.getOwnPropertyNames,
>     getOwnPropertyDescriptor = Object.getOwnPropertyDescriptor
>   ;
>   forEach in ObjectPrototype || Object.defineProperty(
>     ObjectPrototype,
>     forEach,
>     {value: function forEach(callback, context) {
>       for (var
>         self = this,
>         props = getOwnPropertyNames(self),
>         i = 0, length = props.length,
>         key;
>         i < length; ++i
>       ) {
>         callback.call(
>           context,
>           key = props[i],
>           getOwnPropertyDescriptor(self, key),
>           self
>         );
>       }
>     }}
>   );
> }(this.Object));
>
> where an example would be
>
> var o = {a:123};
> o.forEach(function (key, descriptor, obj) {
>   alert([
>     key, // "a"
>     descriptor.value, // 123
>     obj == o, // true
>     this == window // true
>   ]);
> }, this);
>
> consistent with Array.prototype.forEach API while a proper
> Object.prototype.forIn or just Object.forIn may look up until the prototype
> chain is complete ...
>
> (function (Object) {
>   var
>     forIn = "forIn",
>     ObjectPrototype = Object.prototype
>     getPrototypeOf = Object.getPrototypeOf
>   ;
>   forIn in ObjectPrototype || Object.defineProperty(
>     ObjectPrototype,
>     forIn,
>     {value: function forIn(callback, context) {
>       var self = this;
>       do  {
>         self.forEach(callback, context);
>       } while (self = getPrototypeOf(self));
>     }}
>   );
> }(this.Object));
>
> so that
>
> var o1 = {a:123};
> var result = [];
> o1.forIn(function (key, descriptor) {
>   result.push(key, descriptor.value);
> });
> alert(result);
>
> my 2 cents
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.mozilla.org/pipermail/es-discuss/attachments/20120328/118e7bea/attachment.html>


More information about the es-discuss mailing list