admin管理员组文章数量:1317915
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
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
Share Improve this question edited Dec 3, 2012 at 14:45 Denys Séguret 383k90 gold badges810 silver badges775 bronze badges asked Oct 29, 2012 at 14:14 JohanJohan 35.2k62 gold badges187 silver badges305 bronze badges2 Answers
Reset to default 14The 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 pare 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 ifvalueOfElement
is of primitive type
The this
keyword will access the element as a JavaScript object. You can get it's value the same way you would any other JavaScript object, or you can wrap it ($(this)
) to make it into a jQuery object.
本文标签: javascriptjqueryeach()quotthisquot vs valueOfElementStack Overflow
版权声明:本文标题:javascript - jquery.each() - "this" vs valueOfElement - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1742025013a2415377.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论