什么是不可变.js中的“所有者ID”

What is the "ownerID" in Immutable.js?

本文关键字:所有者 ID 中的 不可变 js 什么      更新时间:2023-09-26

我正在浏览不可变.js的源代码,有一个我不明白的ownerID字段。

以下是Map.asMutable()Map.asImmutable()的来源: https://github.com/facebook/immutable-js/blob/master/src/Map.js#L171

似乎可变对象

和不可变对象之间的唯一区别是它们的ownerID。什么是ownerID,它的用途是什么?

如果追溯属性:

L#14:

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

in 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() {}

这是他们创建的一些属性,如哈希来代表虚拟所有者。

它用于确保返回asMutable实例中的可变性。调用 asMutable 时,它会确保__ownerId并返回当前实例 -

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

然后,任何受支持的变异操作都会返回当前实例,而不是使用更改创建新实例(这是不可变性的关键)。

例如,以下是"清除"方法如何基于__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();
}

请注意,当存在this.__ownerID时,该方法返回当前实例(从而改变自身)。但是当它不存在时,它会返回一个新映射以确保不变性。

从源代码:

// 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() {}

我对上述内容的理解是,this.__ownerID字段用于比较对象。一个Map与自身比较将具有相同的ownerID,而与另一个Map进行比较的Map将看到两个不同的ownerID

您可以在相关文件更下方看到此用法的示例:

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

事实上,搜索整个存储库,你会看到此函数在数据类型中是通用的,每种类型都有一个略微修改的版本,以返回该类型的正确新版本。