簡體   English   中英

JavaScript 中帶括號和不帶括號的函數調用區別

[英]Difference of calling a function with and without parentheses in JavaScript

我正在處理 JavaScript 文件上傳事件。 我有以下初始化程序和以下功能:

初始化程序

    $('#s3-uploader').S3Uploader({
        allow_multiple_files: false,
        before_add: progressBar.show,
        progress_bar_target: $('.upload-progress-bar'),
        remove_completed_progress_bar: false
    }).bind("s3_upload_complete", function(e, content) {
        console.log(content);
    });

功能

var progressBar = {
    show: function() {
        $('.upload-progress-bar').show();
        return true;
    }
}

在初始化程序中,我注意到如果我這樣做會有所不同

before_add: progressBar.showbefore_add: progressBar.show() 使用括號,即使綁定到before_add選項,它也會被調用一次,而沒有括號則不會。

對我觀察到的行為有解釋嗎?

括號中的方法被調用,因為括號的,而調用的結果將被存儲在before_add。

如果沒有括號,您可以在變量中存儲對函數的引用(或“指針”,如果您願意的話)。 這樣,每當有人調用 before_add() 時,它就會被調用。

如果這不能解決問題,也許這會有所幫助:

 function Foo() { return 'Cool!'; } function Bar(arg) { console.log(arg); } // Store the >>result of the invocation of the Foo function<< into X var x = Foo(); console.log(x); // Store >>a reference to the Bar function<< in y var y = Bar; // Invoke the referenced method y('Woah!'); // Also, show what y is: console.log(y); // Now, try Bar **with** parentheses: var z = Bar('Whut?'); // By now, 'Whut?' as already been output to the console; the below line will // return undefined because the invocation of Bar() didn't return anything. console.log(z);

如果您隨后查看瀏覽器的控制台窗口,您應該會看到:

Cool!
Woah!
function Bar(arg)
Whut?
undefined

第 1 行是調用Foo()的結果,
第 2 行是調用Bar() "via" y
第 3 行是y的“內容”,
第 4 行是var z = Bar('Whut?'); 線; 調用Bar 函數,
第 5 行顯示調用Bar()並將結果分配給z沒有返回任何內容(因此: undefined )。

函數在 JavaScript 中是一流的。 這意味着它們可以被傳遞,就像任何其他參數或值一樣。 您看到的是傳遞函數和傳遞所述函數返回的值之間的區別。

在你的例子中:

before_add: progressBar.show

您想傳遞progressBar.show而不是progressBar.show()因為前者代表一個函數( function () {$('.upload-progress-bar').show(); return true;} )而后者代表返回的結果 ( true )。

這是另一個例子:

 // All this function does is call whatever function is passed to it var callAnotherFunction = function (func) { return func() } // Returns 3 — that's all var return3 = function () { return 3 } // `callAnotherFunction` is passed `return3` // so `callAnotherFunction` will `return return3()` === `return 3` // so `3` is printed document.write(callAnotherFunction(return3)) // `callAnotherFunction(return3())` is the same as `callAnotherFunction(3)`. // This will print nothing because, in `callAnotherFunction` // `func` is 3, not a function // so it cannot be invoked, so nothing is returned // and `document.write` doesn't print anything. document.write(callAnotherFunction(return3()))

暫無
暫無

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

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