> From: John J Barton <[email protected]>
> Subject: Re: Object.extends (was Re: traits feedback)
> Date: October 7, 2011 16:49:50 GMT+02:00
> To: Quildreen Motta <[email protected]>
> Cc: John-David Dalton <[email protected]>, es-discuss Steen 
> <[email protected]>
> 
> Several people advocate Object.extend() that copies only own properties. I 
> don't understand why; I'll make the case for copying all properties.
> 
> At a call site I use, say  
>    foo.bar(); 
> Ordinarily I should not be concerned about details of bar()'s implementation. 
> In particular I should not be concerned if bar() is own or not. 
> 
> Now I decide to create a new object from |foo|, by adding properties with 
> Object.extend():
>   var fuz = Object.extend(foo, {paper:'in', shoes:'my'});
> later I write
>   fuz.bar();
> 
> If Object.extend() only uses own properties, the success or failure of that 
> statement depends upon the location of bar() in foo.  While one might argue 
> that use of extend() is one case where devs should be concerned with details 
> of bar()'s implementation, how does it help in this case? If bar() is in a 
> prototype then I am back to manual property manipulation get the |fuz| object 
> I want.
> 
> If Object.extend() copies all properties (into prototype or not is a 
> different issue) then the resulting object acts as an extension of the one I 
> want to extend.
> 
> On the other side I don't see any advantage to copying only own properties. 
> Again I will suggest Object.getOwnProperties() as a way of providing the 
> answer some would like to see.  Again I will point out that Object.extend() 
> with plain objects is not affected by these issues.


If you do something like 
     var fuz = Object.extend(foo, {paper:'in', shoes:'my'});

Then fuz will get all properties of Object.prototype, again, as duplicates. In 
the above, you are clearly most interested in what you see in the literal and 
those are the own properties.

Also note that JavaScript only changes properties in the first object in a 
prototype chain:
    var proto = { foo: 3 };
    var obj = Object.create(proto);
    obj.foo = 5;
    console.log(proto.foo); // 3

And this kind of "extend" enables poor man’s cloning as follows:
    var orig = { foo: "abc" };
    var clone = Object.extend(Object.create(Object.getPrototypeOf(orig)), orig);

I would prefer the name Object.copyOwnPropertiesTo(source, target) or 
Object.copyOwnTo(source, target) to the name “extend” (which, to me, suggests 
inheritance).

-- 
Dr. Axel Rauschmayer

[email protected]
twitter.com/rauschma

home: rauschma.de
blog: 2ality.com



_______________________________________________
es-discuss mailing list
[email protected]
https://mail.mozilla.org/listinfo/es-discuss

Reply via email to