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
1.0k views
in Technique[技术] by (71.8m points)

what is the difference between calling function in JavaScript with or without parentheses ()

so a simple example would be

function a() {
    alert("something");
}

anything.onclick = a; // this is without parentheses

anything.onclick = a(); // this is with parentheses 

What is the difference between the two?

And one thing more: if I define the same function but this time return false, will it work?

function a(){
    alert("something");
    return false;
}
See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

The difference is that a() calls the function while a is the function.

console.log( a() ); // false
console.log(  a  ); // function() {...}

To make it clear what technically happens when you use the second part of your example, let's redefine alike this:

a = function() {
    return 100;
};

and set the event handler:

anything.onclick = a();

f() not only calls the function f but returns its return value. So when setting a variable or object property to a function call, the return value of the function call will be assigned. So the above statement is effectlively equivalent to:

anything.onclick = 100;

which doesn't make sense and might cause an error. If a function doesn't have a return value, its return value is implicitly undefined.

However, if you had set a variable equal to a without calling it, it would be the same as setting a regular function expression to that variable:

var a = function() { ... },
    b = a; // b = function() { ... }

b would perform the same operation as a would.

So in your example go with the first one because it makes sense! The only case in which you would assign the return value of the function call to an event handler is if the function returns another function. For instance:

var x = function(xyz) {
    return function() {
        console.log(xyz);
    };
};

anything.onclick = x("Hello World"); // = function() {
                                     //       console.log("Hello World");
                                     //   }

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

...