簡體   English   中英

為什么對匿名函數的此調用不起作用?

[英]Why does this call to anonymous function does not work?

為什么這樣

$( '#someid' ).click( function() {
    getdata( 'listing' , function( data ) {
        showlist( data );
    }, 'string' , 1 );
});

工作,但這個沒有

$( '#someid' ).click( function() {
    getdata( 'listing' , showlist( data ), 'string' , 1 );
});

它不起作用,因為getdata要求一個函數作為第二個參數。 在第二個示例中,您正在執行函數(並傳遞其返回值),而不是傳遞函數本身。

如果你寫

$( '#someid' ).click( function() {
    getdata( 'listing' , showlist, 'string' , 1 );
});

如果沒有parens ()它仍然有效,但是如您所見,您無法再通過showlist函數傳遞data參數

在第二個示例中,您正在執行showlist(data)並將其結果值作為getdata()參數。

您可以想象,這是:

getdata( 'listing' , showlist( data ), 'string' , 1 );

在邏輯上等效:

var temp = showlist( data );
getdata( 'listing', temp, 'string', 1);
function( data ) {
        showlist( data );
    }

表示您正在傳遞匿名函數

showlist( data )

意味着您正在調用showList(data)並將返回的值傳遞給該函數。 如果您想正確使用第二種情況,請按以下步驟解決:

$( '#someid' ).click( function() {
    getdata( 'listing' , showlist, 'string' , 1 );
});

因為第一個傳遞函數作為getdata的第二個參數,而第二個傳遞調用函數的結果

您可以正確地寫第二個

$( '#someid' ).click( function() {
    getdata( 'listing' , showlist, 'string' , 1 );
});

我們不再調用 showlist這里,而允許getdata稍后調用它。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM