[thelist] Extending Javascript Objects
Keith Gaughan
keith at digital-crew.com
Fri Aug 19 10:08:41 CDT 2005
-----BEGIN PGP SIGNED MESSAGE-----
Hash: SHA1
Martyn Haigh wrote:
> I'#m trying to make my life a bit easier, and kinda failing. I've
> written a few JavaScript prototype functions and attached them to the
> Object :
>
> Object.prototype.getStyle = function(strProperty) {
> ...
> }
> Object.prototype.setStyle = function(strPoperty, strValue) {
> ...
> }
> Object.prototype.addClass = function(strClass) {
> ...
> }
> Object.prototype.removeClass = function(strClass) {
> ...
> }
> Object.prototype.replaceClass = function(strOldClass, strNewClass) {
> ...
> }
> Object.prototype.classExists = function(strClass) {
> ...
> }
Everybody else has covered the other issues, but there's one more that I
ought to mention.
<tip title="Never extend the Object prototype in JavaScript">
It's tempting to extend the Object prototype so that you'll have all
these extra methods on all the objects derived from Object. But this
is a *really* bad idea.
You see, doing so makes objects unusable as hashtables. Lets say that
you've done this:
Object.prototype.foo = function() {};
And later on in some completely unrelated code you've got something
that does something like:
var bar = { "Fred": "Wilma", "Barney": "Betty" };
if ("foo" in bar)
{
alert("Whoa! This shouldn't happen!");
}
else
{
alert("All is well: objects behaving as proper hashes.");
}
You'll get a pop-up window saying "Whoa! This shouldn't happen!",
because there's a phantom element in 'bar' called 'foo' from your
extending Object like that.
Erik explains things even better here:
http://erik.eae.net/archives/2005/06/06/22.13.54/
</tip>
K.
-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.4.1 (MingW32)
Comment: Using GnuPG with Thunderbird - http://enigmail.mozdev.org
iD8DBQFDBfX5mSWF0pzlQ04RAtcqAKCSsqB3NddbhuctS/BJPwjNFLzI/QCfa7eR
BzdREvfibyTxeVRrDb4LsgM=
=Pm6w
-----END PGP SIGNATURE-----
More information about the thelist
mailing list