Change context in $ .each ()

I am trying to change the context for the jQuery $.each . What did I miss?

 $.each.call(this, [1,2,3], function(){ console.log(this); // expecting to see the window object }); var foo = { bar: 1 }; $.each.call(foo, [1,2,3], function(){ console.log(this); // expecting to see the foo object }); 

http://jsfiddle.net/53jhrbh5/

+6
source share
3 answers

$.each uses call and apply internally to set the correct this value in the callback, something like callback.apply(obj[i]) , so it uses an array for the value of this and calling the method with call will not change that.

It works something like this.

 function each(obj, callback, args) { var value, i = 0, length = obj.length, isArray = isArraylike(obj); if (args) { if (isArray) { for (; i < length; i++) { value = callback.apply(obj[i], args); } } else { for (i in obj) { value = callback.apply(obj[i], args); } } } return obj; } 

See how it calls the callback, passing each value from the passed array or object as the value of this , which means that you cannot change it by calling the $.each method in different ways, since it has nothing to do with this value with the this value of the jQuery callback function.

You could have $.proxy it or bind() it, but the easy way is to just use a variable

 var self = this; $.each(arr, function() { console.log( self ); }); 
+5
source

There are several ways to do this.

1) Help window outside

 var self = this; $.each.call(this, [1,2,3], function(){ console.log(self); // expecting to see the window object }); 

2) Bind a function to a specific area

 $.each.call(this, [1,2,3], function(){ console.log(this); // expecting to see the window object }.bind(this)); 

3) Use the function with the ES6 arrow, which binds to the current context (cannot be used in most browsers without conversion 6-> 5)

 $.each.call(this, [1,2,3], () => { console.log(this); // expecting to see the window object }); 

4) Direct help window only

 $.each.call(this, [1,2,3], () => { console.log(window); // expecting to see the window object }); 
+3
source

Just use Function.bind in the callback to indicate in which context you want the function to run.

 $.each([1,2,3], (function(){ console.log(this); // expecting to see the window object }).bind(this)); 

Internally, jQuery uses ThisBinding modifiers, such as apply , call . That way, this will always be Number unless you specify the callback context that should be run.

+3
source

Source: https://habr.com/ru/post/982051/


All Articles