Javascript中有和没有括号的调用函数的区别

时间:2015-06-10 09:07:49

标签: 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.show v.s. before_add: progressBar.show()。使用括号,即使它被绑定到before_add选项,它也会被调用一次,而没有括号则不会。

我想知道我观察到的行为是否有任何解释。

2 个答案:

答案 0 :(得分:4)

使用括号,该方法被调用,因为括号的,该调用的结果将存储在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** parenthesis:
var z = Bar('Whut?');

//By now, 'Whut?' as already been output to the console; the below line will
//return undefined because the invokation of Bar() didn't return anything.
console.log(z);
&#13;
&#13;
&#13;

如果您再看一下您的浏览器&#39;您应该看到控制台窗口:

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

第1行是调用Foo()
的结果 第2行是调用Bar() &#34;来自&#34; y的结果,
第3行是&#34;内容&#34; y
第4行是var z = Bar('Whut?');行的结果;栏功能被调用
第5行显示调用Bar()并将结果分配给z并没有返回任何内容(因此: undefined )。

答案 1 :(得分:1)

函数在JavaScript中是一流的。这意味着它们可以传递,就像任何其他参数或值一样。您所看到的是传递函数和传递函数返回值之间的区别。

在你的例子中:

before_add: progressBar.show

您希望传递progressBar.show而不是progressBar.show(),因为前者代表一个函数(function () {$('.upload-progress-bar').show(); return true;}),而后者代表返回的结果(true)。

这是另一个例子:

&#13;
&#13;
// 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 return
// and `document.write` doesn't print anything
document.write(callAnotherFunction(return3()))
&#13;
&#13;
&#13;

相关问题