I am learning the javascript scope chains. When a variable is declared in a function, it can't been seen in another function. For example, myVar is declared in function a and can't been seen in function b:
function b() {
console.log(myVar);
}
function a() {
var myVar = 2;
b();
}
a(); //->myVar is not defined
But why a function can pass its argument to its inner function call (not nested new functions)? Are arguments supposed to be the function's local variables?
function b(str) {
console.log(str);
}
function a(str) {
b(str);
}
a("a's argument"); //->"a's argument"
Yes, but as you pass the str
prop explicitly to the b function, it's valid.
What should not work :
function b() {
console.log(str);
}
function a(str) {
b();
}
a("a's argument"); //->undefined
The fact that the two variables in your example have the same name means nothing, as they're defined in different scopes.
When in function a
you do
b(str);
What you're doing is coping the value of parameter str
in function a
to another variable, the parameter str
in function b
. Internally, variables are just simple ways to referencing memory addresses. When you call b(str)
you're copying into b->str
the same value a->str
holds, but, in the end, you have two different memory addresses containing the same value (the pointer of the a's argument
string).
The JavaScript interpreter/compiler knows that they are two different addresses, as they belong to two different scopes.
If you do:
function b(str) { setTimeout(function() { console.log(str) }, 1000); } function a(str) { b(str); str = 'new value'; console.log(str); } a("a's argument");
You'll see that, despite changing b->str
's value in a
, when the setTimeout
in b
executes, it logs out the original value, even though it is logged after the console.log
in a
which shows the changed value.
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.