Chrome sometimes calls incorrect constructor
google-chrome, javascript, jquery
Solution
The responses in Chromium bug tracker seem to confirm that this is a bug of Chrome browser.
The workaround solution is to "fix" `pushStack()` function in jQuery:
// 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();
// 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.
}
Problem
We have a web site that uses extensively jQuery and it works fine in Firefox and IE. However in Chrome, we are getting frequently (and semi-randomly) `Uncaught TypeError: Cannot call method 'apply' of undefined` (also other jQuery methods appear in place of `apply`). We managed to track down the problem to jQuery method `pushStack()`. Original source code (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.) } ``` Instrumented code: ``` pushStack: function( elems, name, 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.) } ``` In most cases `pushStack()` runs correctly. However sometimes Chrome constructs an object of type `Object` instead of `jQuery.fn.init`. Console output: ``` 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> ``` Did anybody encounter similar problem? Is it a (known) bug of Chrome? Update I managed to simplify our page, so that it could be loaded on its own. I filled bug in Chromium project project, the page for reproducing the issue is attached there.