3
$.each(["foo","bar"],function(){console.debug(this);});

will convert "foo" and "bar" of string type to their equivalent in string object.

whereas...

$.each(["foo","bar"],function(i,e){console.debug(e);});

will keep "foo" and "bar" in their original string type.

I wonder why does $.each do the conversion? And, more to the point... should this conversion never happen - leave strings as they are, whether they are of string type, or of string object?

2 Answers 2

2

According to the jQuery documentation:

(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.)

This indicated that it's Javascript, not jQuery that's doing the conversion.

In the case of using the value in the callback function, jQuery passes that value itself and thus it can retain its type.

Sign up to request clarification or add additional context in comments.

1 Comment

I believe the javascript behavior in question that causes this is the call() function, which autoboxes primitives.
1

jQuery isn't to blame here: it's a quirk of JavaScript. As defined in ECMAScript Third Edition section 10.4.3, when you call a function, the this pseudo-argument is manipulated: notably, a null value is converted to the global object (window), and primitive values are auto-boxed:

3) Else if Type(thisArg) is not Object, set the ThisBinding to ToObject(thisArg).

Parameters don't get mangled in the same way, which is why the second argument to each() is more reliable.

There's no particular rationale for JavaScript doing this, it's just one of the crazy things Netscape did back in the day, that then had to be standardised in ECMAScript. In Fifth Edition's Strict Mode, this curious behaviour goes away.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.