Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
104 views
in Technique[技术] by (71.8m points)

Difference of calling a function with and without parentheses in JavaScript

I was handling a JavaScript file upload event. And I have the following initializer and the following function:

Initializer

    $('#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);
    });

Function

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

In the initializer, I noticed there is a difference if I do

before_add: progressBar.show v.s. before_add: progressBar.show(). With the parentheses, it will be called once even if it is bound to the before_add option, and without the parentheses it will not.

Is there an explanation for the behaviour I observed?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

With parentheses the method is invoked because of the parentheses, and the result of that invocation will be stored in before_add.

Without the parentheses you store a reference (or "pointer" if you will) to the function in the variable. That way it will be invoked whenever someone invokes before_add().

If that didn't clear things up, maybe this will help:

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);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...