Re: Iterating over the properties of an ECMAScript object

On Thu, Apr 17, 2014 at 4:13 AM, David Bruant <bruant.d@gmail.com> wrote:

> Hi Brian,
>
> Le 17/04/2014 08:21, Brian Birtles a écrit :
>
>  Hi,
>>
>> In Web Animations we support a kind of open-ended dictionary so that
>> authors can write:
>>
>>   elem.animate({ opacity: '1', marginTop: '20px' }, 2000);
>>
>> The keys 'offset' and 'marginTop' correspond to properties and attributes
>> the UA can animate.
>>
>> WebIDL doesn't allow this so we defined our own handling.[1]
>>
>> To iterate over the passed in object's properties we decided to use
>> Object.keys()
>>
> Don't use Object.keys literally since authors may redefine it at runtime
> (and it wouldn't be what you expect). I'd recommand using an internal
> operation.
>
>
>  so we only visit enumerable properties on the object itself. Does this
>> seem reasonable? Or should we visit non-enumerable properties or properties
>> on prototypes?
>>
> I think that for this sort of cases, it makes sense to visit inherited
> properties (so authors can define a default set of properties and override
> via prototype shadowing creating an object with `Object.create(defaultObj)`)
> ES6 defines an internal [[Enumerate]] operation for all objects
> http://people.mozilla.org/~jorendorff/es6-draft.html#sec-
> ordinary-object-internal-methods-and-internal-slots-enumerate
> It's what is used by for-in loops (enumerate over own and inherited
> enumerable properties). Maybe that's what you should use.
>

Agreed, and a step further would be to specify that only valid properties
are recognized. Here's a naive hack to illustrate:

// ...some object of allowed properties, eg. the object returned by
getComputedStyle
// provides a suitable source of allowable CSS properties.
var allowed =  getComputedStyle(elem);

//...
for (var p in o) {
  if (typeof allowed[p] !== "undefined") {
    ... p is an allowed property.
  }
}


Like I said, "a naive hack".

Rick

Received on Thursday, 17 April 2014 18:09:17 UTC