+ 6
Can anyone explain this to me?
var y = 7 ; function func(x) { x = 4 } ; func(y) ; document.write(y) Why is the output 7, not 4? Please explain!
9 Antworten
+ 7
Nothing changes the value of "y" so it stays the same.
+ 7
It should be written "y = func(y)", got it?
+ 5
But x is a parameter, it's not a variable...
+ 5
Why does func(y) not change the value of y?
+ 5
y = func(y) is only if func(x) has a return value of 4.
+ 5
Even if func() had return, "y" value wouldn't change.
+ 3
'y' variable is passed to function 'func' by value: the value of 'y' is duplicated, and set to the argument variable 'x' value.
Inside 'func', the value of variable 'x' is modified, then the function end, and its scope too: var 'x' and its value are deleted ( precisly: garbage collected ^^ ).
During all this time, the value of 'y' stay unchanged, just have been reading when the call of the function occured, to COPY the value in function parameters...
The trap is, when passing objects ( all non basic type, including arrays ), variables are passing by reference, which means without duplicate it, so will be modified if the function change their values!
+ 1
Because there is no return.
The variable x which has a scope only within the function is 4
If you would document.write(x) in the function the output would be 4
0
when you call fanc(y) here is the logic of what happens... x becomes equal to y then x becomes equal to 4. y doesn't change.