JavaScript 中带括号和不带括号的函数调用区别

IT技术 javascript
2021-03-09 00:23:32

我正在处理 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选项,它也会被调用一次,没有括号则不会。

对我观察到的行为有解释吗?

2个回答

括号中的方法被调用,因为括号的,并且结果该调用的将被存储在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()))