[英]Is func() the same as func?
While learning JavaScript from an "eloquent" book, I stumbled in this program:在从一本“雄辩”的书中学习 JavaScript 时,我偶然发现了这个程序:
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
.我的问题是 output 是
wrap1()
而不是wrap1
。
Is it possible to do even console.log(wrap1)
?甚至可以做
console.log(wrap1)
吗?
And if it's possible, are wrap1()
and wrap1
the same thing?如果可能的话,
wrap1()
和wrap1
是一样的吗?
EDIT: they flagged the question as duplicate of What is the difference between a function call and function reference?编辑:他们将问题标记为 function 调用和 function 参考之间有什么区别? however my problem was thinking that in
let wrap1 = wrapValue(1);
但是我的问题是在
let wrap1 = wrapValue(1);
, wrap1
gets a value, but the truth is that it gets a function. ,
wrap1
得到一个值,但事实是它得到一个 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. wrapValue 返回 lambda function,这是
console.log(wrap1)
将打印的内容。 console.log(wrap1())
actually runs that function and prints the result. console.log(wrap1())
实际上运行 function 并打印结果。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.