我们有一个广泛使用jQuery的网站,它在Firefox和IE中工作正常.但是在Chrome中,我们越来越频繁(半随机)未捕获TypeError:无法调用未定义的方法“apply”(也可以使用其他jQuery方法代替apply).
我们设法将问题跟踪到jQuery方法pushStack().
原始源代码(jQuery 1.7.1):
// Take an array of elements and push it onto the stack
// (returning the new matched element set)
pushStack: function( elems,name,selector ) {
// Build a new jQuery matched element set
var ret = this.constructor();
// (etc.)
}
仪器代码:
pushStack: function( elems,selector ) {
if (!(this instanceof jQuery.fn.init)) throw this;
// Build a new jQuery matched element set
var ret = this.constructor();
if (!(ret instanceof jQuery.fn.init)) {
console.log("pushStack>this: " + this.constructor);
console.log("pushStack>ret: " + ret.constructor);
throw ret;
}
// (etc.)
}
在大多数情况下,pushStack()正确运行.但是有时Chrome会构造Object对象而不是jQuery.fn.init.控制台输出:
pushStack>this: function ( selector,context ) {
// The jQuery object is actually just the init constructor 'enhanced'
return new jQuery.fn.init( selector,context,rootjQuery );
}
pushStack>ret: function Object() { [native code] }
Uncaught #<Object>
有人遇到类似的问题吗?这是Chrome的(已知的)bug吗?
更新
我设法简化了我们的页面,以便它可以自己加载.我填补了bug in Chromium project项目,复制问题的页面附在那里.
解决方法
Chromium bug tracker中的回复似乎证实这是Chrome浏览器的错误.
解决方法是在jQuery中“修复”pushStack()函数:
// Take an array of elements and push it onto the stack
// (returning the new matched element set)
pushStack: function( elems,selector ) {
// Build a new jQuery matched element set
var ret = this.constructor();
// Workaround for Chrome bug
if ((this instanceof jQuery.fn.init) && !(ret instanceof jQuery.fn.init)) {
// console.log("applying pushStack fix");
ret = new jQuery.fn.init();
}
// etc.
}