Javascript functions question, could someone possibly help explain?
I am currently trying to learn Javascript and understand that functions are one of the most important aspects of the language but I have to say Im finding it very hard to understand them especially when different parameters are bein开发者_JAVA技巧g used here there and everywhere.
I have been looking at this code which I read in another stack overflow post regarding closure and cant understand how 16 is alerted, I have used console.log to work out what value is being used at each point and seem to get a total of 17, could someone possibly explain?
function foo(x) {
// console.log(x); = 2
var tmp = 3;
return function (y) {
// console.log(y); = 10
alert(x + y + (++tmp));
// console.log(++tmp); = 5?
}
}
var bar = foo(2);
bar(10);
If anyone can offer any wisdom about functions that might make things start to make sense for me it would be really appreciated.
Kyle
The alert()
command really pops up 16.
++tmp
is preincrement statement - first, it increments the value (from 3 to 4) and then continues with execution of the line.
So 2 + 10 + 4
is passed to the alert()
.
The console.log(++tmp)
below the alert logs 5, because the tmp
variable is incremented again, from 4 to 5.
Try to log
console.log(tmp);
Instead of
console.log(++tmp);
foo(2)
initializes tmp
to 3 and x
to 2 within the scope of the returned function.
bar(10)
then adds 2, 10, and the result of incremented tmp
(which went from 3 to 4 before being added to x
and y
).
so the alerted value will be the sum of 2 + 10 + 4.. 16.
精彩评论