为什么使用immutable js

2016-07-07

JavaScript 中的对象一般是可变的(Mutable),因为使用了引用赋值,新的对象简单的引用了原始对象,改变新的对象将影响到原始对象。如 foo={a: 1}; bar=foo; bar.a=2 你会发现此时 foo.a 也被改成了 2。虽然这样做可以节约内存,但当应用复杂后,这就造成了非常大的隐患,Mutable 带来的优点变得得不偿失。

some problems

  1. Mutable objects complect Time and Value
    1
    2
    3
    4
    var id;
    id = 'value';
    id = 'next value';
    id = 'future value';

Immutable data removes complexity

  1. Mutator problem
    1
    2
    3
    4
    5
    function touchAndPrint(fn) {
    var data = { key: "value" };
    fn(data);
    console.log(data.key);// ? hell
    }

what changed ?

1
2
3
4
5
var dataStore = { key:"value" };
render(dataStore);
loadDataIntoStore(url, ()=>{
render(dataStore);
});

Object.observe(); es7

1
2
3
4
5
6
var dataStore = {key:"value"};
render(dataStore);
Object.observe(dataStore, chages => {
render(dataStore, changes);
});
loadDataIntoStore(url);