jQuery: The Write Less, Do More JavaScript Library

Ticket #1585 (closed bug: fixed)

Opened 1 year ago

Last modified 1 year ago

namespace.jQuery() fails when namespace.init is defined

Reported by: arrix Assigned to: anonymous
Type: bug Priority: major
Milestone: 1.2.1 Component: core
Version: 1.2 Keywords:
Cc: Needs: Review

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

Change History

Changed 1 year 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

Changed 1 year 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.

Changed 1 year ago by john

  • status changed from new to closed
  • resolution set to fixed

Fixed in SVN rev [3298].

Note: See TracTickets for help on using tickets.