Bug Tracker

Ticket #6461 (closed bug: worksforme)

Opened 5 years ago

Last modified 3 years ago

Difference in $.each() between 1.3.2 and 1.4.2

Reported by: lillq Owned by:
Priority: Milestone: 1.4.3
Component: traversing Version: 1.4.2
Keywords: each Cc:
Blocking: Blocked by:

Description

In the following code the value of this is different between 1.3.2 and 1.4.2

In 1.3.2 in the each loop below (typeof this === string).

But in 1.4.2 in the each loop below (typeof this === object).

Thus in the loop below the classes are not removed from the elements due to the (this) not being a string in 1.4.2.

/The Code*/

var myArray = ['class1', 'class2', 'class3', 'class4'];

jQuery(function() {

elements = $('div.class1'); jQuery.each(myArray, function() {

elements.removeClass(this);

}); alert(elements.attr('class'));

});

Change History

comment:1 Changed 5 years ago by lillq

Better formatted code:

/****************The Code***********************/ var myArray = ['class1', 'class2', 'class3', 'class4'];
jQuery(function() {
elements = $('div.class1');
jQuery.each(myArray, function() {
elements.removeClass(this);
});
alert(elements.attr('class'));
});

comment:2 Changed 4 years ago by spudly

Same problem here. For some reason 'this' is ALWAYS an object, not just a string or number. Here's the code I'm using:

$.each( [ 1 ], function () {

alert( this === 1 );

});

Why is jQuery.each changing the data type of the variable?

comment:3 Changed 4 years ago by dmethvin

  • Status changed from new to closed
  • Resolution set to worksforme

It's not jQuery, it's Javascript. $.each uses the Function.call method to invoke the callback. The code there has not changed from 1.3.2 to 1.4.2.

 https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Objects/Function/call

If thisArg is null or undefined, this will be the global object. Otherwise, this will be equal to Object(thisArg) (which is thisArg if thisArg is already an object, or a String, Boolean, or Number if thisArg is a primitive value of the corresponding type). Therefore, it is always true that typeof this == "object" when the function executes.

Note: See TracTickets for help on using tickets.