问题
I want to know the differences between:
$('a').map(function(){return this})
$.map($('a'), function(){return this})
They behave differently when I test them in firebug console.
回答1:
Having just briefly tested, they do perform differently. 'this' in the context of the latter references the window object. However you do have access the current element when looping through the object/array passed in:
$('a').map(function(){
return this
});
$.map($('a'), function(el){
return el;
});
The latter is typically used for non-jQuery objects and arrays, whereas the former is for this purpose.
See the documentation for more information:
http://api.jquery.com/map/
http://api.jquery.com/jQuery.map/
回答2:
There is no difference and i think that
$('a').map(function(){return this})
is a wrapper around
$.map($('a'), function(){return this})
in fact this is the jQuery source code
map: function( callback ) {
return this.pushStack( jQuery.map(this, function( elem, i ) {
return callback.call( elem, i, elem );
}));
},
EDIT - of course (i gave that for granted) this refers to the current element when you call .map() on a collection while it refers to the window object when you iterate over a collection with $.map()
来源:https://stackoverflow.com/questions/10121810/this-keyword-in-jquery-map