for..in, hasOwnProperty(), and inheritance

Felipe Gasper felipe at felipegasper.com
Tue Nov 8 13:08:30 PST 2011



On 11/8/11 2:19 PM, Brendan Eich wrote:
> On Nov 8, 2011, at 12:12 PM, Luke Smith wrote:
>
>>> Sure. People make "classes" by defining function C(){} and decorating C.prototype.method1 = function(...){...}, etc. A for-in loop on (new C) will see all the methods, unlike the case with built-in constructors. That is an unwanted abstraction break: we should support abstracting over user-defined and built-in functions.
>> I believe people decorate a class prototype directly because they
>> always have, and because defineProperties wasn't available for them to
>> declare prototype methods as not enumerable, not because they
>> explicitly want class proto methods to be enumerable.
>
> Yup, that's a fact. However it contradicts Felipe's belief that only
> Object.prototype might-be-enumerable properties need to be excluded,
> which was my point.

Wasn’t so much a *belief* as an observation that the reasons most folks 
give for wanting the hasOwnProperty() check in for..in loops are similar 
to what Crockford wrote here:
http://www.yuiblog.com/blog/2006/09/26/for-in-intrigue/

…i.e., the “main” concern, esp. if you inherit objects from just 
anywhere (e.g., YUI’s config objects), is Object.prototype.


The case Brendan mentions is closer to what I had in mind as a reason 
for the more fine-grained control of gave(). In Brendan’s case:
-------
function C(){}; C.prototype.foo = function(){};
var my_c = new C(); my_c.bar = null;
-------

…it makes sense to weed out stuff from the prototype. Even then, though, 
it might be equally, or more, gainful to check for:
-------
for (key in my_c) {
     if ( !C.gave(key,my_c) ) { … }
}
-------

…or, at least, there could be multiple use cases, e.g. multiple levels 
of inheritance, and I want to filter out either *just* the original 
(gave/giver) or all prototypes (hasOwnProperty()).

Anyhow. Thanks to everyone for the bandwidth on the idea.

-FG


More information about the es-discuss mailing list