Why don't parameters retain their value outside of a function?
This question already has an answer here:
What is the explanation for this weird behavior?
Because in Javascript variables are function scoped.
You never passed a
and b
to myTest
method. You passed 8 and 5, so a
and b
which were part of myTest
signature got new scope. a
became 8 and b
became 5 inside myTest
.
Values of a
and b
inside myTest
will not be used outside since their scope is limited to myTest.
Inside your function, you have a local a
parameter. So any changes you make to that value, they will not reflect your globally defined a
. Since you did not create a c
variable or parameter inside the function, you will be changing the global c
value.
var c = 0; // Global c
var a = 0; // Global a
var b = myTest(8, 5); // Store the value of the local a from the function return.
function myTest(a,b) {
console.log(a); // This a is a local reference (8)
a++; // Increment local a
c++; // Increment global c
console.log(a); // Print local a (9)
return a; // Return local a
}
console.log(a); // Print global a (0)
console.log(c); // Print global c (1)
console.log(b); // Print returned value (9)
链接地址: http://www.djcxy.com/p/40836.html
上一篇: Javascript自动getter / setters(John Resig Book)
下一篇: 为什么参数在函数外保留其值?