Preom
Preom

Reputation: 1680

Using call on $.each

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?

Upvotes: 2

Views: 35

Answers (2)

rism
rism

Reputation: 12142

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'}) );

Upvotes: 0

guest271314
guest271314

Reputation: 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>

Upvotes: 1

Related Questions