stavo esaminando come UnderscoreJS implementa il loro each
/forEach
sottolineatura di ogni controllo per {} ritorno di callback
//somewhere up top:
var breaker = {};
//then the each function
var each = _.each = _.forEach = function (obj, iterator, context) {
if (obj == null) return;
if (nativeForEach && obj.forEach === nativeForEach) {
obj.forEach(iterator, context);
} else if (obj.length === +obj.length) {
for (var i = 0, l = obj.length; i < l; i++) {
if (iterator.call(context, obj[i], i, obj) === breaker) return;
}
} else {
for (var key in obj) {
if (_.has(obj, key)) {
if (iterator.call(context, obj[key], key, obj) === breaker) return;
}
}
}
};
//iterator = callback
//context = optional third parameter of each to provide context in the callback
//obj = the list
//key = key of the object (i for index when an array)
In sostanza, si tratta di eseguire il callback per ogni elemento nell'oggetto/array. Ma questo, come mi confonde
if (iterator.call(context, obj[key], key, obj) === breaker) return;
Da quello che ho capito, se la richiamata restituisce un oggetto, le pause del ciclo, ma ... perché è confrontandole con breaker
che è un oggetto interno nel modulo di sottolineatura?. Non valuta in ogni momento fino a false
poiché, anche se la richiamata restituisce un oggetto, è sempre false
poiché non è lo stesso oggetto (quindi il ciclo non si interrompe mai). Qual è la ragione di questo?
Un altro trucco che mi piace, se è necessario aggiungere valori agli oggetti dell'interruttore è invece di creare una classe Breaker e utilizzare i test instanceof. – hugomg