4

If I extend the Object prototype and try to use some functions of jQuery 2.0.3 I get errors...

For example jsFiddle

Object.prototype.GetHashCode = function() { return 1; };
$(document).on("click", "div", function() { });

If I do this and then click any div I get an error

Uncaught TypeError: Object function () { return 1; } has no method 'exec' 

Why does it happen? Is there a workaround or a way to fix this bug in jQuery?

BrunoLM
  • 97,872
  • 84
  • 296
  • 452
  • 1
    possible duplicate of [How to define method in javascript on Array.prototype and Object.prototype so that it doesn't appear in for in loop](http://stackoverflow.com/questions/13296340/how-to-define-method-in-javascript-on-array-prototype-and-object-prototype-so-th) – Bergi Sep 10 '13 at 17:05
  • @Chandu: OK, it doesn't exactly answer the question. *Why does this happen?* - because you're destroying all `for in` property enumerations with extending the `Object.prototype`. It is not a bug in jQuery. *Is there a workaround?* - see the linked duplicate – Bergi Sep 10 '13 at 17:11
  • 1
    Seems like a jquery bug...by the way this works fine `$('div').click(function() { console.log('div clicked'); });` – NaveenBhat Sep 10 '13 at 17:55
  • 1
    @NaveenBhat: No, it is not a jQuery bug. It is just that a `for in` loop is used in the code when a delegated event is triggered, but not for a directly attached handler. – Bergi Sep 10 '13 at 18:26
  • You *really* shouldn't extend `Object.prototype`. – gen_Eric Sep 10 '13 at 18:42
  • Stop saying I shouldn't use without a reasonable explanation why I shouldn't. – BrunoLM Sep 10 '13 at 18:43
  • 1
    possible duplicate of [Why does this JavaScript prototype function break jQuery?](http://stackoverflow.com/questions/14941657/why-does-this-javascript-prototype-function-break-jquery) – bfavaretto Sep 16 '13 at 18:58

1 Answers1

5

In this report they say they don't want to fix that. So don't use Object.prototype when working with jquery.

georg
  • 211,518
  • 52
  • 313
  • 390