javascript 将函数存储为变量

gev0vcfq  于 2023-02-02  发布在  Java
关注(0)|答案(6)|浏览(173)

我试图理解将函数存储为变量。如果我有以下函数:

function calc() {

     return 2 * 2 

}

calc() //returns 4

var test = calc() 

test // returns 4

我知道变量test的值为4,这是有意义的。
但是,在本例中:

function foo() {

     console.log("HEY")

  }

 foo() //logs "HEY" in the console

 var test = foo() 

 test // does NOT log "HEY" in the console.

为什么不遵循同样的模式呢?

but5z9lq

but5z9lq1#

var test = foo()没有将函数foo存储到变量test中,它在test中存储foo的 * 返回值 *,并且由于foo没有指定返回值,所以存储在test中的值将是undefined
进一步解释:在函数名或对函数的引用后放置括号将调用该函数。要只引用函数而不调用它,请在准备调用它之前不要使用括号。例如:

function foo() {
  console.log("HEY")
}

foo() // "HEY"

var test = foo; // no () here

test() // use () here. "HEY"
b91juud3

b91juud32#

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()
svdrlsy4

svdrlsy43#

而是关于回归一些事情!
当你在fn下面调用时,它返回一个值

var calc = function () { return 2*2; }

如果你认为这是在做什么!

var foo = function () { console.log("hey"); }

这意味着,当你调用calc fn时,你需要给它赋一个变量

var result = calc();

如果要记录一些内容,只需调用foo(不赋值)

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!
webghufk

webghufk4#

()调用函数并返回一个值,因此括号需要为var test = foo test()

wgeznvg7

wgeznvg75#

// 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());
cuxqih21

cuxqih216#

您需要执行以下操作:返回“嘿”;而不是console.log(嘿);

相关问题