jQuery conflict with native prototype

后端 未结 2 1043
萌比男神i
萌比男神i 2021-01-05 15:55

I have a problem using jQuery with native JavaScript (NOT prototype.js). When using the following code, jQuery 1.9.1 with an error message:

         


        
相关标签:
2条回答
  • 2021-01-05 16:18

    There is no safe way in older browsers to extend Object.prototype without breaking jQuery. The jQuery authors specifically say (somewhere...) that jQuery will break if you just add new enumerable properties to Object.prototype.

    The only safe way requires ECMAScript 5, and its Object.defineProperty function, which allows non-enumerable properties to be added to objects.

    The jQuery noconflict() function doesn't help - it's a solution to an entirely different problem.

    0 讨论(0)
  • 2021-01-05 16:22

    You can avoid these problems by making your extensions to the native prototypes as non-enumerable:

    Object.defineProperty(Object.prototype, 'myVeryGreatFunction',{
      value : function() {},
      enumerable : false
    });
    

    Object.defineProperty documentation on MDN

    As Jan Dvorak mentioned, this solution does not work for old browsers (IE8-).

    0 讨论(0)
提交回复
热议问题