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
The answer is in the documentation you linked to :
All values are embedded in objects when accessed as
this.The real reason can be found in this line of jQuery source :
You can compare it to
which builds a
Number, because you can’t call a function on something that isn’t an object.From MDN on the call function :
The only advantages I would see in using
thisinstead ofvalueOfElementare :thiseven ifvalueOfElementis of primitive type