Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
150 views
in Technique[技术] by (71.8m points)

javascript - jquery.each() - "this" vs valueOfElement

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...