javascript immutable.js

javascript - ¿Qué es el "ownerID" en Immutable.js?



(3)

Desde el código fuente :

// A function which returns a value representing an "owner" for transient writes // to tries. The return value will only ever equal itself, and will not equal // the return of any subsequent call of this function. function OwnerID() {}

Mi comprensión de lo anterior es que el campo this.__ownerID se usa para comparar objetos. Un Map está comparando con sí mismo tendrá el mismo ownerID , mientras que un Map se compara con otro Map verá dos ownerID diferentes.

Puede ver un ejemplo de este uso un poco más abajo en el archivo en cuestión :

__ensureOwner(ownerID) { if (ownerID === this.__ownerID) { return this; } if (!ownerID) { this.__ownerID = ownerID; this.__altered = false; return this; } return makeMap(this.size, this._root, ownerID, this.__hash); }

De hecho, al buscar en todo el repositorio , verá que esta función es común en todos los tipos de datos, y cada tipo tiene una versión ligeramente modificada para devolver una nueva versión correcta de ese tipo.

Estoy revisando el código fuente de ownerID y hay un campo ownerID que no entiendo.

Aquí está la fuente de Map.asMutable() y Map.asImmutable() : https://github.com/facebook/immutable-js/blob/master/src/Map.js#L171

Parece que la única diferencia entre un objeto mutable y un objeto inmutable son sus ownerID . ¿Qué es un ownerID y para qué se utiliza?


Se utiliza para garantizar la mutabilidad en asMutable devuelto instancias. Cuando se invoca asMutable , garantiza un __ownerId y devuelve la instancia actual de nuevo -

asMutable() { return this.__ownerID ? this : this.__ensureOwner(new OwnerID()); }

Luego, cualquier operación de mutación supported devuelve la instancia actual, en lugar de crear una nueva instancia con los cambios (que es clave para la inmutabilidad).

Por ejemplo, aquí es cómo funciona el método "claro" basado en la presencia de __ownerId -

clear() { if (this.size === 0) { return this; } if (this.__ownerID) { this.size = 0; this._root = null; this.__hash = undefined; this.__altered = true; return this; } return emptyMap(); }

Tenga en cuenta que cuando este .__ ownerID está presente, el método devuelve la instancia actual ( mutando así a sí mismo). Pero cuando está ausente, devuelve un nuevo mapa para garantizar la inmutabilidad.


Si realiza un seguimiento de la propiedad:

L # 14:

import { DELETE, SHIFT, SIZE, MASK, NOT_SET, CHANGE_LENGTH, DID_ALTER, OwnerID, MakeRef, SetRef, arrCopy } from ''./TrieUtils''

en src / TrieUtils.js :

L # 36:

// A function which returns a value representing an "owner" for transient writes // to tries. The return value will only ever equal itself, and will not equal // the return of any subsequent call of this function. export function OwnerID() {}

Es una propiedad que crean como hash para representar a un propietario virtual.