开发者

Augmenting Object object with a function that all objects can use

My motivation for the augmentation of Object is I want to be able to easily handle objects meant to simply store data (like a "hashmap" in Java). I want to easily do hashmap.size().

Let's say my object has a property called objData which was empty when made like this:

var objData = {};

My object has some methods that can add data to objData like this:

this.objData[key1name] = data1;

And my object also has some methods which access objData:

if(this.objData.size() == 0):

Of course, no such method exists. So that's my motivation for augmenting the Object object:

        Object.prototype.getOwnPropertyCount = function ( ) {
            var count = 0;
            for(var item in this) {
                if (this.hasOwnProperty(item)) {
                    count += 1;
                }
            }
            return count;
        };

Now I should be able to do either:

开发者_Go百科
if (this.objData.getOwnPropertyCount() == 0)

or:

if(!objData.getOwnPropertyCount())

But in actuality I get errors when I try to load the page completely unrelated to any code I've written. I'm getting errors thrown in google maps api's main.js. Voodoo.

So I change my augmentation to augment the actual Object instead of Object.prototype:

Object.getOwnPropertyCount = function ( ) {
    //calculate the count
    return count;
};

And now I get the following error in Firefox:

this.objData.getOwnPropertyCount is not a function

What am I missing here?


When you move your method declaration from Object.prototype directly to the Object constructor, the method is no longer available in the prototype chain of all objects (a good thing BTW), I would suggest you to provide your function an argument, to pass the object you need to opearate, and change your method call:

// from `this.objData.getOwnPropertyCount()` to:
Object.getOwnPropertyCount(this.objData);

And obviously, in your implementation, you should count the properties of the passed object, since this, will refer to the Object constuctor, in the above example.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜