[thelist] Extending Javascript Objects

Jeffery To jeffery.to at gmail.com
Sun Aug 21 01:27:08 CDT 2005

On 8/21/05, Matt Warden <mwarden at gmail.com> wrote:
> Yeah, that's true. Using Object is safer than using any of its
> subclasses. Still, if someone were to try to set add a property named
> '__foo__' to Object:
> Object.prototype.__foo__ = 'bar';
> it would most certainly conflict with a key named 'foo' in the hashtable.

You can avoid getting properties from the Object prototype by using
hasOwnProperty(). For example in SimpleHashtable_get():

var val = (this._data[key] && this._data.hasOwnProperty(key)) ?
this._data[key] : null;

In fact, unless I'm mistaken, it should be safe to extend the Object
prototype if you always test with hasOwnProperty() before trusting a
property. For instance:

for (var i in obj) {
    if (obj.hasOwnProperty(i)) {
        /* do things */

There are a few caveats with hasOwnProperty():
1) DOM elements in IE don't contain this method, but extended
properties in the Object prototype aren't inherited by DOM elements in
IE anyway;
2) hasOwnProperty() isn't supported in IE 5.0 [1], Safari [2] and Mac
IE 5.2 [2]. I've been working on a replacement function, but I'm not
bold enough to let anyone see it before I clean it up a bit.


[1] http://msdn.microsoft.com/library/default.asp?url=/library/en-us/script56/html/js56jsmthhasownproperty.asp
[2] http://phrogz.net/JS/hasOwnProperty.html

Jeffery To

More information about the thelist mailing list