I want to write a function like jQuery each and am using the javascript call function.
function each(array, callback) {
for (var i=0; i<array.length; i++) {
console.log(typeof(array[i])); // Number
callback.call(array[i]);
}
}
each([1,2,3], function() {
console.log(typeof(this)); // Object
});
The problem is call seems to be casting Number types to Object types. This causes issues with the console.log call. Can anyone explain why this is happening (my guess is that call casts arguments to type Object). Why would it do this? Can you figure out a way to work around or prevent this?
This is a requirement of the specification when not in strict mode.
If you use the
"use strict";declarative at the top of your code, you’ll get whatever actual value you passed.DEMO: http://jsfiddle.net/agXkZ/
Note that strict mode is lexically scoped, so you could add the declarative to the callback only if you’d prefer.
DEMO: http://jsfiddle.net/agXkZ/1/
If you don’t want to use strict mode, you can (in this case) convert to a primitive by using the unary
+operator.DEMO: http://jsfiddle.net/agXkZ/2/
Related information:
From ECMAScript 5 Annex E (informative) Additions and Changes in the 5th Edition that Introduce Incompatibilities with the 3rd Edition:
And ECMAScript 5 Annex C (informative) The Strict Mode of ECMAScript: