jquery.each() - “this” vs valueOfElement

后端 未结 2 1570
[愿得一人]
[愿得一人] 2020-12-10 06:47

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

Example:

<
相关标签:
2条回答
  • 2020-12-10 07:07

    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.

    0 讨论(0)
  • 2020-12-10 07:13

    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
    0 讨论(0)
提交回复
热议问题