[英]How to point already declared javascript function to a variable
如果我想先声明一个函数,然后在某个时候我想引用该函数而不是将其返回值引用到变量,我该怎么做?
var best = bestPresidentEver;
function bestPresidentEver(a,b){
//for some reason always returns Trump.
}
and then call best(a,b) instead of bestPresidentEver(a,b)
我想知道如何做到与声明时将函数分配给var相反。
var best =
function bestPresidentEver(a,b){
//for some reason always returns Trump.
}
这样声明您的变量
var bestPresidentEver= function (a,b){
//for some reason always returns Trump.
return "Trump"; //:D
}
然后像这样调用该函数
//You have to declare a and b variables
var trumpHere = bestPresidentEver(a,b);
如果已经声明了函数,则将其分配给变量:
function bestPresidentEver (a,b){
//for some reason always returns Trump.
return "Trump"; //:D
}
var trumpHere = bestPresidentEver;
然后这样称呼它:
var trumpAgain = trumpHere(a, b);
如果变量存在并且不是const
,则可以将其值重新分配给函数本身。 防爆
var foo = 'foo';
function bar(a) {
return 'example ' + a;
}
bar('code'); //=> "example code"
/* Further down, reassign the `foo` variable */
foo = bar;
foo('code, again'); //=> "example code, again"
我正在使用SignalR,我需要将其指向一个函数,并且我还想在应用程序的其他区域中调用该函数。
如果库需要一个函数参数,则可以像这样简单地传递该函数。
function first(next /* expects a function parameter */) {
return next('hello');
}
function second(prefix) {
return prefix+ ' world!';
}
first(second); //=> "hello world!"
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.