我在将 jQuery 与 native JavaScript(不是 prototype.js)结合使用时遇到问题。使用以下代码时,jQuery 1.9.1 会出现错误消息:
Object.prototype.myVeryGreatFunction = function() {
// ...
}
[Error] TypeError: undefined is not a function (evaluating 'U[a].exec(s)')
ft (jquery.min.js, line 4)
wt (jquery.min.js, line 4)
st (jquery.min.js, line 4)
find (jquery.min.js, line 4)
init (jquery.min.js, line 3)
b (jquery.min.js, line 3)
(anonymous function) (read.control.js, line 59)
c (jquery.min.js, line 3)
fireWith (jquery.min.js, line 3)
ready (jquery.min.js, line 3)
H (jquery.min.js, line 3)
当我删除原型(prototype)定义时,一切正常。不幸的是,我无法轻松更新 jQuery,因为它位于 CMS 的插件中,因此出于兼容性原因,它必须与旧版本一起使用。
是否有任何已知问题或修复方法?
Google 实际上向我展示了使用 jQuery.noConflict()
和私有(private)函数包装等解决方案。但是如上所述,我没有使用 prototype.js,而是使用native JS 对象原型(prototype)。
最佳答案
您可以通过将对 native 原型(prototype)的扩展设为不可枚举来避免这些问题:
Object.defineProperty(Object.prototype, 'myVeryGreatFunction',{
value : function() {},
enumerable : false
});
Object.defineProperty
关于 MDN 的文档
正如 Jan Dvorak 提到的,此解决方案不适用于旧浏览器 (IE8-)。
关于javascript - jQuery 与 native 原型(prototype)冲突,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21729895/