/    Sign up×
Community /Pin to ProfileBookmark

Weird change of order in cloned prototype

I use this code to clone an object. At the end I test the properties:

[code]
//cloning codes
function Clone(){}
function clone(obj) {
Clone.prototype = obj;
return new Clone();
}
//
var Orange={nature:’fruit’,color:’orange’}
var Banana=clone(Orange);
for(a in Banana){
alert(a)
}
[/code]

So far so good. I see: nature – > color
But now I want to change a property of the Banana object, the color, then test again the properties:

[code]
Banana.color=’green’;
for(a in Banana){
alert(a)
}
[/code]

Surprisingly, the changed property becomes the first in the loop, which is curious. I see now: color – > nature

Can anyone explain me why? I understand that the last [I]new[/I] created property comes (why?) always first (which I don’t like, but I take it as it is), but I suppose that, in the case above, the property was already defined, and I did nothing but changing its [I]value[/I].

Is there a way to keep the order within the prototype members?


Additional note: The worse thing is that the order changes within the browsers. FF and IE act different. Is there any standard for that? Who does not follow it?

to post a comment
JavaScript

1 Comments(s)

Copy linkTweet thisAlerts:
@KeverMar 30.2011 — I ran into that before, there is no standard enumeration order for objects. Maybe they added it to ECMA 5.

If I need to keep order to my output I always create an extra array, where I specify the properties in the order I need.
<i>
</i>Orange.toString = function(){
var order = ['nature', 'color'];
for(var i=0; i&lt;order.length; i++)
print(Orange[order[i]]);
};
×

Success!

Help @Kor spread the word by sharing this article on Twitter...

Tweet This
Sign in
Forgot password?
Sign in with TwitchSign in with GithubCreate Account
about: ({
version: 0.1.9 BETA 5.8,
whats_new: community page,
up_next: more Davinci•003 tasks,
coming_soon: events calendar,
social: @webDeveloperHQ
});

legal: ({
terms: of use,
privacy: policy
});
changelog: (
version: 0.1.9,
notes: added community page

version: 0.1.8,
notes: added Davinci•003

version: 0.1.7,
notes: upvote answers to bounties

version: 0.1.6,
notes: article editor refresh
)...
recent_tips: (
tipper: @AriseFacilitySolutions09,
tipped: article
amount: 1000 SATS,

tipper: @Yussuf4331,
tipped: article
amount: 1000 SATS,

tipper: @darkwebsites540,
tipped: article
amount: 10 SATS,
)...