I am trying to understand storing a function as a variable. If I have the following function:
function calc() {
return 2 * 2
}
calc() //returns 4
var test = calc()
test // returns 4
I know that the variable test
has the value of 4, which makes sense.
However, in this example:
function foo() {
console.log("HEY")
}
foo() //logs "HEY" in the console
var test = foo()
test // does NOT log "HEY" in the console.
Why does that not follow the same pattern?
答案 0 :(得分:7)
var test = foo()
does not store the function foo
into the variable test
, it stores the return value of foo
in test, and since foo
doesn't return anything, the value stored in test
will be undefined
.
Further explanation: Placing parentheses after a function name or a reference to a function will call that function. To just reference the function without calling it, simply don't use parentheses until you're ready to call it. For example:
function foo() {
console.log("HEY")
}
foo() // "HEY"
var test = foo; // no () here
test() // use () here. "HEY"
答案 1 :(得分:1)
function foo() {
console.log("HEY")
}
foo() //logs "HEY" in the console
//correct way
// foo() is calling the function and asigning its return value
// foo is the function
var test = foo
//then we call the stored function
test()
答案 2 :(得分:0)
it's about returning and doing something!
when you call below fn, it's returning a value
var calc = function () { return 2*2; }
if you call this, it's doing something!
var foo = function () { console.log("hey"); }
that means, when you call calc fn, you need to assign it a variable
var result = calc();
if you want to log something, you just call foo (not assign)
foo(); // log appears on the fly
var bar = foo(); // log appears again but since foo is not return something bar will be nothing
// assign fn to variable, so now you can call variable!
bar = foo; // no log, wait for the call
bar(); // log appears!
答案 3 :(得分:-1)
You need to do: return "hey"; instead of console.log(hey);
答案 4 :(得分:-1)
// This does the console.log as soon as it is called - it does not store the response and wait until a later time.
function foo() {
console.log("hey");
}
// If you wanted to console.log something when you assign the variable, you can do this:
function foo() {
return "hey";
}
var test = foo();
console.log('test: ', test);
// or this:
function foo() {
return "hey";
}
var test = console.log(foo());