Javascript lexical scoping
Can someone开发者_StackOverflow社区 please explain in plain language how this code works to give a result of 9?
what happens to the return of the inner function? Im assuming that the enclosing function return is assigned to the variables addTwo and addFive... where does the inner function get its argument (number)? I
m totally lost on this and the tutorial doesn`t explain it.
function makeAddFunction(amount) {
function add(number) {
return number + amount;
}
return add;
}
var addTwo = makeAddFunction(2);
var addFive = makeAddFunction(5);
show(addTwo(1) + addFive(1));
var addTwo = makeAddFunction(2);
1. 2
is assigned as amount
and bound within the function scope. The inner add
function has access to this, and so keeps it "cached".
So what is returned is essentially function(number) { number + 2 };
var addFive = makeAddFunction(5);
2. 5
is assigned the same way, and function(number) { number + 5 };
is returned.
show(addTwo(1) + addFive(1));
3. function( number ) {number+2}
is invoked and 1
is fed to the function, so 2+1
is returned which is 3
.
4. function( number ){number+5}
is invoked and 5
is fed to the function, so 5+1
is returned which is 6
.
5. 6
and 3
are added, so we get 9
.
6. 9
is fed to the show
function.
makeAddFunction
returns function add
that adds number to amount.
in line var addTwo = makeAddFunction(2);
you've created a function with amount
2.
If you call that function(addTwo
) with some number, it return 2 + passed argument
By this logic: addTwo(1) = 2 + 1 = 3
,
addFive(1) = 5 + 1 = 6
6 + 3 = 9
精彩评论