是否从另一个不可变的Map中为一个Map指定一个对象意味着深度克隆?

时间:2016-05-10 02:29:13

标签: javascript immutable.js

当我有两个不可变的Map对象时:

const MapA = Immutable.fromJS({person: {name: 'Peter', age: 18}, parent: 'Sally'});
let MapB = Immutable.fromJS({prop1: 'testing'});

MapB = MapB.set('person', MapA.get('person'));

对象{name:'Peter',年龄:18}是在两张地图中分享还是有共享方式?

1 个答案:

答案 0 :(得分:1)

ImmutableJS分享实例。在您的情况下,MapA和MapB共享快照实例person。您可以通过在此实例上添加自定义纯JS属性来验证这一点,并对MapA版本和MapB版本进行验证。你会发现它们具有相同的值。

这里有一个小提琴...... https://jsfiddle.net/HaZardous/0Ls5gdht/

这里是小提琴代码 -

var MapA = Immutable.fromJS({person: {name: 'Peter', age: 18}, parent: 'Sally'}),
MapB = Immutable.fromJS({prop1: 'testing'}),
person = MapA.get('person');

MapB = MapB.set('person', person);

person["nationality"] = "US";

console.log("Direct ref: " + person["nationality"]);
console.log("MapA ref: " + MapA.get('person')["nationality"]);
console.log("MapB ref: " + MapB.get('person')["nationality"]);

输出

Direct ref: US
MapA ref: US
MapB ref: US