leaflet.js lettura del', mi sono imbattuto in un metodo con questa linea, che io non comprendo pienamente:Assegnazioni multiple var a = b = b || {} Nel codice javascript
var events = this._leaflet_events = this._leaflet_events || {};
che può essere semplificata come
var a = b = b || {};
Da quello che ho capito questa istruzione è un compito più mancino che è associativa destra che significa che prima, JavaScript verrà eseguito
b = b || {} //if b exists, returns b, else return an empty object
, poi
a = b // returns the output of the preceding instruction
Quale non ha senso per me. Perché non scrivere invece:
a = b || {};
contesto completa:
addEventListener: function(/*string*/ type, /*function */ fn, /*(optional) object*/ context){
var events = this._leaflet_events = this._leaflet_events || {};
events[type] = events[type] || {};
events[type].push({
action: fn,
context: context || this
});
return this;
}
ho il sospetto un trucco di riferimento dal momento che non vedo come this._leaflet_events
viene modificata dal metodo altrimenti.
Pensandoci bene, la scrittura var a = b = b || {}
è in realtà essere un trucco per assegnare var a
un riferimento a b
, non importa se b
è definita o no. La modifica di a
ora modifica b
.
Torna a Leaflet. Con
var events = this._leaflet_events = this._leaflet_events || {};
this._leaflet_events
esiste o è inizializzato a {}
. events
è assegnato a this._leaflet_events
come riferimento. Il valore di riferimento potrebbe essere {}
ma è ancora this._leaflet_events
che viene modificato quando si modifica events
.
Al contrario, crei
var events = this._leaflet_events || {};
sarebbe un errore, poiché se this._leaflet_events
non è definito, events
sarà ora puntare a un nuovo oggetto il cui valore sarà {}
. La modifica di events
cambierà il nuovo oggetto ma non cambierà il valore di this._leaflet_events
.
Stessi valori apparenti, riferimenti diversi. Ecco la cosa.
FYI, 'this._leaflet_events' è diverso da' this._leaflet. events'. –
Errore mio, ho modificato il post – cedricbellet