javascript closures and object reference

前端 未结 2 1561
故里飘歌
故里飘歌 2021-01-22 04:10

i am a bit obscure situation. mainly because i thought i already grasp closures. so basically what i want is to reset to default values a collection. so let say i have collectio

2条回答
  •  生来不讨喜
    2021-01-22 04:29

    In javascript, composite data types are passed by reference, so, c.internalarray and arr both refer to the same value. Actually, you were on the right way, but you have to make a copy of the array before passing it to your immediately invoked function. For example :

    c.on('reset', function (arr) {
        return function () {
            c.internalarray = arr;
        }
    }(c.internalarray.slice()));
    

    That said, this technique will not create a deep copy, meaning that composite types contained in the array are still mutable from the outside of the immediately invoked function. In the code below, I've tried to simplify this situation in order to make things easier to understand, hopefully :

    The variable a refers to an array which contains two elements :

    var a = [
        1, // primitive value
        {} // composite value
    ];
    

    Let's make a shallow copy of a and assign it to b :

    var b = a.slice();
    // a -> [1, {}]
    // b -> [1, {}]
    // b === a -> false
    

    Removing the first element from a has no effect on b :

    a.shift();
    // a -> [{}]
    // b -> [1, {}]
    

    But modifying the object contained in a affects b as well :

    a[0].k = 'value';
    // a -> [{ k: "value" }]
    // b -> [1, { k: "value" }]
    // a[0] === b[1] -> true
    

提交回复
热议问题