>
> > Touching prototype of native Object is also very fragile and basically
> > forbidden by most javascript gurus I have read. It can break anything.
>
> But why should it? And if I choose a free name for the new function,
> then why should anybody bother? Google Maps API must be investigating
> its environment and actively decide to break if anything is
> "modified". Different browsers define different functions, too, and it
> shouldn't break.
No, that's not what the problem is.
You've probably used a "for..in" loop to iterate over an object, yes? For
example:
var object = { a:1, b:2, c:3 };
for( var key in object ) {
console.log( key, object[key] );
}
That should log in Firebug or equivalent:
a 1
b 2
c 3
(If you see a gray 'undefined' at the end, that's just because this script
as a whole doesn't return a value.)
Now let's add your function:
Object.prototype.myTest = function () {
return 1;
};
var object = { a:1, b:2, c:3 };
for( var key in object ) {
console.log( key, object[key] );
}
And it logs this instead:
a 1
b 2
c 3
myTest function()
Oops.
What happened? When you add a property or method to Object.prototype, that
name gets enumerated in every "for..in" loop - including loops in other
people's code who weren't expecting it!
It's possible to write "defensive" for loops that filter out your
Object.prototype extensions, but it's a nuisance and makes the code a bit
slower.
So, as much as we'd all like to be able to add new Object methods, it just
isn't done. (Case in point: Prototype.js, which extended Object.prototype in
its early versions but stopped doing it quite some time ago.)
-Mike
--
You received this message because you are subscribed to the Google Groups
"Google Maps JavaScript API v3" group.
To post to this group, send email to [email protected].
To unsubscribe from this group, send email to
[email protected].
For more options, visit this group at
http://groups.google.com/group/google-maps-js-api-v3?hl=en.