Bug Tracker

Opened 13 years ago

Closed 13 years ago

#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:
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 ?!!!!

Change History (3)

comment:1 Changed 13 years ago by arrix

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

comment:2 Changed 13 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.

comment:3 Changed 13 years ago by john

Resolution: fixed
Status: newclosed

Fixed in SVN rev [3298].

Note: See TracTickets for help on using tickets.