Javascript order of referencing

前端 未结 4 1222
不思量自难忘°
不思量自难忘° 2020-12-07 05:25

What order does the following statement run? Does the runtime execute it from right to left?

  length = i = test = output = null;
相关标签:
4条回答
  • 2020-12-07 06:01

    That single line assignment is equivalent to this

    output = null;
    test = output;
    i = test;
    length = i;
    
    0 讨论(0)
  • 2020-12-07 06:07

    Yes, it executes from right to left. The value of everything is now null.

    0 讨论(0)
  • 2020-12-07 06:13

    Does the runtime execute it from right to left?

    Yes.

    foo = {
        set a() {
            console.log('a');
        },
        set b() {
            console.log('b');
        },
        set c() {
            console.log('c');
        },
        set d() {
            console.log('d');
        }
    };
    foo.a = foo.b = foo.c = foo.d = 'bar';
    

    produces:

    d
    c
    b
    a
    

    in the console. This order is necessary because each assignment relies on the return value of the previous assignment:

    foo.a = foo.b = foo.c = foo.d = 'bar';
    

    is equivalent to:

    foo.a = (foo.b = (foo.c = (foo.d = 'bar')));
    

    However it is not equivalent to:

    foo.d = 'bar';
    foo.c = foo.d;
    foo.b = foo.c;
    foo.a = foo.b;
    

    The return value of a = b is b. This is especially important to remember should you choose to implement accessors and mutators.

    What this means is that my previous example is equivalent to:

    foo.d = 'bar';
    foo.c = 'bar';
    foo.b = 'bar';
    foo.a = 'bar';
    
    0 讨论(0)
  • 2020-12-07 06:17

    Yes, since an assignment expression is not a lefthand-side expression itself, the nesting is

    (length = (i = (test = (output = null))));
    

    It is executed from outside-in, solving references left-to-right (first getting the length variable, then evaluating the right side, which is getting the i variable and evaluating …). That means output is the first variable that is getting assigned to, then test, then i, and last length: "right-to-left" if you want. Since the assignment operator always yields its right operand, everything will be assigned the same (innermost, rightmost) value: null.

    0 讨论(0)
提交回复
热议问题