[英]How to point already declared javascript function to a variable
If I wanted to first declare a function, and then at some point I want to reference the function and not its return value to a variable, how would I do that? 如果我想先声明一个函数,然后在某个时候我想引用该函数而不是将其返回值引用到变量,我该怎么做?
var best = bestPresidentEver;
function bestPresidentEver(a,b){
//for some reason always returns Trump.
}
and then call best(a,b) instead of bestPresidentEver(a,b)
I am wondering how to do that opposed to assigning the function to the var upon declaration. 我想知道如何做到与声明时将函数分配给var相反。
var best =
function bestPresidentEver(a,b){
//for some reason always returns Trump.
}
Declare your variable like this 这样声明您的变量
var bestPresidentEver= function (a,b){
//for some reason always returns Trump.
return "Trump"; //:D
}
Then call that function like this 然后像这样调用该函数
//You have to declare a and b variables
var trumpHere = bestPresidentEver(a,b);
If your function is already declared, just assign it to the variable : 如果已经声明了函数,则将其分配给变量:
function bestPresidentEver (a,b){
//for some reason always returns Trump.
return "Trump"; //:D
}
var trumpHere = bestPresidentEver;
Then call it like this : 然后这样称呼它:
var trumpAgain = trumpHere(a, b);
If the variable exists and it's not a const
you can simply reassign it's value to the function itself. 如果变量存在并且不是
const
,则可以将其值重新分配给函数本身。 Ex 防爆
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"
I am using SignalR, and I need to point it to a function, and I also want to call that function in other areas of the application.
我正在使用SignalR,我需要将其指向一个函数,并且我还想在应用程序的其他区域中调用该函数。
If the library expects a function parameter, you can simply pass that function like so. 如果库需要一个函数参数,则可以像这样简单地传递该函数。
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.