“this” keyword in jQuery.map()

主宰稳场 提交于 2019-12-22 00:05:05

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!