Skip to main content

Bug Tracker

Side navigation

#1585 closed bug (fixed)

Opened September 11, 2007 04:03PM UTC

Closed September 15, 2007 02:24AM UTC

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:
Blocked by: Blocking:
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 ?!!!!

Attachments (0)
Change History (3)

Changed September 12, 2007 03:43AM UTC by arrix comment:1

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

Changed September 12, 2007 03:49AM UTC by arrix comment:2

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.

Changed September 15, 2007 02:24AM UTC by john comment:3

resolution: → fixed
status: newclosed

Fixed in SVN rev [3298].