While learning JavaScript from an "eloquent" book, I stumbled in this program:
function wrapValue(n) {
let local = n;
return () => local;
}
let wrap1 = wrapValue(1);
let wrap2 = wrapValue(2);
console.log(wrap1());
// → 1
console.log(wrap2());
// → 2
My problem is the output being wrap1()
rather than wrap1
.
Is it possible to do even console.log(wrap1)
?
And if it's possible, are wrap1()
and wrap1
the same thing?
EDIT: they flagged the question as duplicate of What is the difference between a function call and function reference? however my problem was thinking that in let wrap1 = wrapValue(1);
, wrap1
gets a value, but the truth is that it gets a function. That's it. The supposed duplicate have nothing to do with my blindness.
wrapValue returns a lambda function, which is what console.log(wrap1)
will print. console.log(wrap1())
actually runs that function and prints the result.
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.