If I call a function like this:
var n = 0; f(n, n += 100)
the values of it's arguments are 0 and 100, not 100 and 100 as I would have expected. This behavior does what I currently need i开发者_运维知识库n my program but I don't understand why it works this way and it troubles me.
Can someone explain why it happens so and whether it's safe to pass arguments like this?
The first parameter value is evaluated before the second one.
Unlike C (and like Java), Javascript does in fact have a defined order of argument evaluation: left-to-right. So, somewhat surprisingly, it is safe to write the code as you have. However, I would consider it very poor style and in fact almost unreadable since not many people know off the top of their heads whether the evaluation order is in fact defined (case in point: I had to look it up to answer this question).
Edit: See section 11.2.4 http://www.ecma-international.org/publications/files/ECMA-ST/Ecma-262.pdf
The variable n
is a primitive type in JavaScript (the primitive types include numbers, string, and boolean values). Primitive types are passed by value, explaining the behavior you observed. If n
were a non-primitive type, it would be passed by reference and any modifications made to it would be reflected in all references to n
.
See JavaScript: Passing by Value or by Reference for additional information.
精彩评论