Use "this" as a function?

I inherited some code with a string that I don't understand.

function updateQty () { obj.find('.inputAmount').html(qty); input.val(qty); $.each(change_actions, function() { this(qty); }); } 

What exactly happens inside the .each function? I had never seen this(var) use this path before.

+6
source share
3 answers

the author sets up his own events with bindings, so the chances of change_actions are functions that are signed to run when something happens to the quantity.

Try something like this:

 // initialize with a value var actions = [ function(x){ console.log('I see a new x: ' + x); } ]; // add actions "later" actions.push(function(x){ console.log('Yup, a new x: ' + x); }); // Then execute them: $.each(actions, function(){ this(4); }); // add another one still actions.push(function(x){ console.log(x + ' looks new'); }); // re-iterate over them // Then execute them: $.each(actions, function(){ this(5); }); 

and the result:

 // first iteration (only 2 subscribed events) [15:56:50.030] "I see a new x: 4" [15:56:50.030] "Yup, a new x: 4" // second iteration (now we have 3, one was added later) [15:56:50.030] "I see a new x: 5" [15:56:50.030] "Yup, a new x: 5" [15:56:50.030] "5 looks new" // <-- new subscription 

think of it as a click event and how to add subscriptions by binding to $('element').click() . every time a click occurs, any signed events are fired.

+3
source

this inside $.each refers to the current objects you are viewing.

An object must be a function in order to pass something to it.

+5
source

You can refer to the following example:

 var change_actions = [ function(x) { alert(x + 1); }, function(x) { alert(x + 2); } ]; var qty = 5; $.each(change_actions, function() { this(qty); }); 

JSFiddle: http://jsfiddle.net/fuyz2/

+3
source

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


All Articles