2013-07-24 12 views
6

Ho ereditato del codice con una riga che non capisco.L'uso di "questo" come funzione?

function updateQty() { 
     obj.find('.inputAmount').html(qty); 
     input.val(qty); 

     $.each(change_actions, function() { 
      this(qty); 
     }); 
    } 

Che cosa sta succedendo esattamente all'interno della funzione .each? Non ho mai visto this(var) usato in questo modo prima.

+9

change_actions deve essere una matrice di funzioni. in js semplice, funziona come: function apply (v) {return this (v);} [1,2,3] .map (applica, RegExp); – dandavis

+0

Aggiungere 'console.log (this)' o 'console.dir (this)' al corpo del callback e vedere a cosa si riferisce questo. – fardjad

+0

La funzione $ .each() può essere utilizzata per iterare su qualsiasi raccolta, indipendentemente dal fatto che si tratti di un oggetto o di un array. Nel caso di un array, il callback riceve ogni volta un indice di array e un valore di array corrispondente. (È possibile accedere al valore anche tramite questa parola chiave ...) da qui: http://api.jquery.com/jQuery.each/ – svillamayor

risposta

3

il setup autore i propri eventi con attacchi, così è probabile che change_actions sono funzioni che vengono sottoscritte da eseguire quando succede qualcosa a la quantità.

provare qualcosa di simile:

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

e il risultato:

// 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 

Pensate a come l'evento click e come è possibile aggiungere le sottoscrizioni legandosi al $('element').click(). ogni volta che si verifica un clic, vengono attivati ​​tutti gli eventi sottoscritti.

5

this all'interno di $.each si riferisce agli oggetti correnti che si stanno eseguendo.

L'oggetto deve essere una funzione per passare qualcosa ad esso.

3

Si può riguardare al seguente esempio:

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/

Problemi correlati