Multiple assignment confusion

前端 未结 3 2070
离开以前
离开以前 2020-12-15 07:54

I understand that the assignment operator is right associative.

So for example x = y = z = 2 is equivalent to (x = (y = (z = 2)))

3条回答
  •  别那么骄傲
    2020-12-15 08:15

    Edited the answer to make it simple

    First of all you have to understand the differnce between Reference- and Value- Type.

    var foo = {};
    

    foo variable holds a Reference to an object in memory, lets say A

    Now, there are two arts of accessors: Variable Accessor and Property Accessor.

    So foo.x = foo = {a:1} can be understood as

    [foo_VARIABLE_ACCESSOR][x_PROPERTY_ACCESSOR] = [foo_VARIABLE_ACCESSOR] = {a:1}
    

    !!! Accessor chain is evaluated first to get the last accessor, which is then evaluated associative.

    A['x'] = foo = {a:1}
    

    Property Accessor are seperated into setters and getters

    var foo = { bar: {} };
    foo.bar.x = foo = {a:1}
    

    Here where have decared two nested objects foo and bar. In memory we have then two object A and B.

    [foo_VAR_ACCESSOR][bar_PROP_GETTER][x_PROP_ACCESSOR] = [foo_VAR_ACCESSOR] = {a:1}
    
    > A[bar_PROP_GETTER][x_PROP_ACCESSOR] = [foo_VAR_ACCESSOR] = {a:1}
    > B[x_PROP_ACCESSOR] = [foo_VAR_ACCESSOR] = {a:1}
    > B['x'] = foo = {a: 1}
    

    Here you have little example

    var A = {};
    var B = {}
    Object.defineProperty(A, 'bar', {
        get () {
            console.log('A.bar::getter')
            return B;
        }
    })
    Object.defineProperty(B, 'x', {
        set () {
            console.log('B.x::getter')
        }
    });
    
    var foo = A;
    foo.bar.x = foo = (console.log('test'), 'hello');
    
    // > A.bar.getter
    // > test
    // > B.x.setter
    

提交回复
热议问题