Javascript multiple assignment statement

前端 未结 6 1915
小鲜肉
小鲜肉 2021-01-03 10:28

I saw that line in some code

window.a = window.b = a;

How does it work?

Does the following always return true?

win

相关标签:
6条回答
  • 2021-01-03 11:05

    It's the same like:

    window.b=a;
    window.a= window.b;
    

    window.a == a will be true in this case, after the statements above. There are some cases that it will be false, for example: when a is a global variable.

    And one more thing: please find more informative title for your question next time.

    0 讨论(0)
  • 2021-01-03 11:11

    Actually, window.a==a can be false if a has the value Number.NaN. That's because Number.NaN is not equal to any value, including itself.

    0 讨论(0)
  • 2021-01-03 11:15

    it means

    window.b=a;
    window.a=a;
    

    OR You can say.

    window.b=a;
    window.a=window.b;
    

    two assignments in a single statment

    and

    And one more thing

    window.a==a right?

    yes this is Right. It will return true

    0 讨论(0)
  • 2021-01-03 11:15

    The a and b properties on the window are being assigned to the value of a. Yes, if this code is executed in the global scope, a and window.a are the same.

    var a = "foo";
    
    //window.a and a are the same variable
    window.a = "bar";
    a; //bar
    
    function f(){
        var a = "notfoo";
    
        //window.a is a different variable from a, although they may take the same value
        window.a = "baz";
        a; //notfoo
    }
    
    0 讨论(0)
  • 2021-01-03 11:20

    Same as:

    window.b = a;
    window.a = a;
    

    And no, window.a and a is not always equal. Typically it is only equal on the global scope in a web browser JavaScript interpreter.

    0 讨论(0)
  • This assignment runs from right to left, so at first 'window.b' will be assigned with 'a' value then 'window.a' will be assigned with 'windows.b' value.

    You can break this multiple assignment like this and get the same results:

    window.b=a;
    window.a=a;
    

    You should be also aware of something like scoping. If you run this code in global scope, eg simple script like this:

    <script>
        var a = 10;
        window.a = window.b = a;
    </script>
    

    window.a==a is true, because 'a' and 'window.a' are the same variables. 'a' is really a property of 'window' object. All global variables are properties of 'window' object. Knowing that you can write you code like this, and this code will be corresponnding:

    <script>
        var a = 10;
        a = b = a;
    </script>
    

    But if you put this code in a function, it runs in function scope, eg:

    <script>
        function ex() {
            var a = 10; // this is local variable
            window.a = window.b = a; // this time window.a != a
        }
    </script>
    
    0 讨论(0)
提交回复
热议问题