[英]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.