2

I've tried the following piece of code:

$.each.call({foo: 'bar'}, [1,2,3], function(i){console.log(i, this);})

I thought it would print out {foo: 'bar'} for the this value, but instead it prints the item (which is the expected behavior for $.each). Can someone explain why the this value isn't being overwritten?

2 Answers 2

1

The reason this set to obj appear to be these portions of jQuery.each() source

value = callback.apply(obj[i], args);

and

value = callback.call(obj[i], i, obj[i]);

where callback is function passed to jQuery.each() with obj set as this : array or object arguments passed to each for iteration

function (obj, callback, args) {
    var value, i = 0,
        length = obj.length,
        isArray = isArraylike(obj);

To set this at jQuery.each() callback , try using Function.prototype.bind() on callback function passed to jQuery.each(obj, callback)

$.each([1,2,3], function(i){console.log(i, this);}.bind({foo:"bar"}))
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js">
</script>

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

Comments

0

Also note that you don't need jquery for these type of operations as you can just use plain javascript:

 [1,2,3].map(function(i){ console.log(i, this); }.bind({foo:'bar'}) );

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.