简体   繁体   中英

Variable reassignment in OOP languages

I was playing around with some variables today to get a better feel for them and I came across something that looks peculiar to me. Here's an example in JavaScript

var foo = "Sethen";
var bar = foo;
var bar = "Sethen is " + bar;
console.log(bar);

We get the output of Sethen is Sethen which is not what I would expect. What I am seeing is an assignment to bar and then another assignment to bar that overwrites the bar value. I would expect to see instead Sethen is Sethen is . This also happens in PHP. Is there something fundamental I am missing here?

Why does this work as Sethen is Sethen when bar is getting assigned twice??

bar is assigned after computing the right-hand side expression.

Most assignment operators in a lot of languages have a very low precedence when it comes to order of operations.

Mozilla has a whole document on the operator precedence of JavaScript.

The expression "Sethen is " + bar; is executed before the assignment

除了运算符优先级之外,您还需要了解运算符的关联性-http://en.wikipedia.org/wiki/Operator_associativity

when you want to evaluate an expression in any language, the compiler( interpreter in js ) first evaluate the computational portion of the expression(right side), then it stores(assigns) the evaluated value to a variable. in this case you first have assigned "Sethen" to variable bar through var bar = foo; in the next line you have an expression in which the compiler first evaluate "Sethen is " + bar; , which bar now(before assignation) holds "Sethen" .the evaluation leads to "Sethen is Sethen" .then the compiler assigns the computed value to the bar variable.after all steps, when you print the result, you see "Sethen is Sethen" .

       step 1:
             var foo="sathen";
             It store string "sathen" in foo

        step 2:
              var bar=foo;
              bar value contains foos value now bar="sathen" and foo="sathen"

        step 3:     
              var bar= "sathen is " + bar
              it will replce the value of bar in right side is "sathen is" +bar value4
                 "sathen"  
         So,your ans will come "sathen is sathen"         

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM