Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jquery.each() - "this" vs valueOfElement

In a jQuery.each() loop, I always thought that this was equivalent to valueOfElement. Could someone explain the difference?

Example:

$.each(object, function(i, val){
    $('body').append('<b>valueOfElement:</b> ' + typeof val + ' - ' +  
    '<b>this: </b>' + typeof this + '<br/>');
});

Result:

valueOfElement: string - this: object
valueOfElement: boolean - this: object
valueOfElement: object - this: object

Fiddle

like image 602
Johan Avatar asked Oct 29 '12 14:10

Johan


People also ask

What is the use of jQuery each () function?

each(), which is used to iterate, exclusively, over a jQuery object. The $. each() function can be used to iterate over any collection, whether it is an object or an array. In the case of an array, the callback is passed an array index and a corresponding array value each time.

Can we use foreach in jQuery?

Learn how to loop through elements, arrays and objects with jQuery using the $. each() function, jQuery's foreach equivalent. jQuery's foreach equivalent can be very useful for many situations. These examples will get you started and teach you how you can loop through arrays, objects and all kinds of HTML elements.

Is jQuery each asynchronous?

each is synchronous, but the code inside might not be... each itself is processed synchronously.

How do you iterate through an element in jQuery?

The . each() method is designed to make DOM looping constructs concise and less error-prone. When called it iterates over the DOM elements that are part of the jQuery object. Each time the callback runs, it is passed the current loop iteration, beginning from 0.


1 Answers

The answer is in the documentation you linked to :

The value can also be accessed through the this keyword, but Javascript will always wrap the this value as an Object even if it is a simple string or number value.

All values are embedded in objects when accessed as this.

The real reason can be found in this line of jQuery source :

callback.call( obj[ i ], i, obj[ i++ ] ) === false ) {

You can compare it to

(function(){console.log(this)}).call(1);

which builds a Number, because you can't call a function on something that isn't an object.

From MDN on the call function :

thisArg :

Note that this may not be the actual value seen by the method: if the method is a function in non-strict mode code, null and undefined will be replaced with the global object, and primitive values will be boxed.

The only advantages I would see in using this instead of valueOfElement are :

  • simplicity : you don't have to keep in mind the order of arguments given to the callback
  • ability to use a function directly on this even if valueOfElement is of primitive type
like image 58
Denys Séguret Avatar answered Nov 08 '22 12:11

Denys Séguret