Kyle Macey
Kyle Macey

Reputation: 8154

Extending Object causes jQuery error

So I wrote a function to extend Objects to count how many entries are within them, so it may be used as such:

test = {"foo": "bar", "baz": 7, "darth": "maul"}

test.count()
=> 3

I wrote the code as such:

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

This is my first attempt at extending with prototype, and I'm getting this error from within jQuery.js:

Uncaught TypeError: Object function () {
  var count = 0, key;
  for (key in this) {
    if (this.hasOwnProperty(key)) {
      count++;
    }
  }
  return count; 
} has no method 'replace'

The stacktrace points back to where I call css on a jQuery object onLoad:

$img.css({left: 20, top: 50});

Not that I think there's anything specific about that line, but I thought it may be good to provide.

Is there something I'm doing wrong here?

Upvotes: 0

Views: 704

Answers (1)

Jamie Treworgy
Jamie Treworgy

Reputation: 24334

A lesson in why it can be a bad idea to extend the prototype of native types. :)

Somewhere in jQuery, it's testing a generic object for the existence of a property called count, and then treating it as a string. Since you've now caused that property to always exist, it found it, but it wasn't a string (as it expected) and broke the code.

Upvotes: 2

Related Questions