Ticket #1585 (closed bug: fixed)
namespace.jQuery() fails when namespace.init is defined
| Reported by: | arrix | Owned by: | |
|---|---|---|---|
| Priority: | major | Milestone: | 1.2.1 |
| Component: | core | Version: | 1.2 |
| Keywords: | Cc: | ||
| Blocking: | Blocked by: |
Description
Now jQuery can be assigned to any custom namespace. But the following code will fail
var ns = {
init: function() {/*...*/},
jQuery: jQuery
};
var j = ns.jQuery('#id');
Patch
Index: E:/zm/jquery/jquery/src/core.js
===================================================================
--- E:/zm/jquery/jquery/src/core.js (revision 3251)
+++ E:/zm/jquery/jquery/src/core.js (working copy)
@@ -14,8 +14,8 @@
var _jQuery = jQuery;
var jQuery = window.jQuery = function(a,c) {
- // If the context is global, return a new object
- if ( window == this || !this.init )
+ // If the context is a namespace object, return a new object
+ if ( !(this instanceof jQuery) )
return new jQuery(a,c);
return this.init(a,c);
In the patch, I'm using this instanceof jQuery instead of this.constructor == jQuery because (new jQuery()).constructor == Object ?!!!!
Change History
comment:2 Changed 6 years ago by arrix
I thought about removing the return statement in the jQuery constructor but that would break things.
In my testing, if a constructor returns a non-primitive object, the returned object will the value of the new expression.
e.g.
function F() {return [];};
var f =new F(); // => []
f.constructor; // => Array
f instanceof F; // => false
Since jQuery.fn.init may return a new jQuery object instead of this, we have to keep the return statement in jQuery constructor.
Please follow the bug reporting guidlines and use jsFiddle when providing test cases and demonstrations instead of pasting the code in the ticket.

Index: E:/zm/jquery/jquery/src/core.js =================================================================== --- E:/zm/jquery/jquery/src/core.js (revision 3258) +++ E:/zm/jquery/jquery/src/core.js (working copy) @@ -14,11 +14,8 @@ var _jQuery = jQuery; var jQuery = window.jQuery = function(a,c) { - // If the context is global, return a new object - if ( window == this || !this.init ) - return new jQuery(a,c); - - return this.init(a,c); + // If the context is a namespace object, return a new object + return this instanceof jQuery ? this.init(a,c) : new jQuery(a,c); }; // Map over the $ in case of overwrite