When assigning the function to onclick dynamically, what is the difference between two of the following.
1...
button.onclick=function(){funct(this.value)};
2...
button.onclick=funct(this.value);
where funct is some other function.
Are these two equivalent?
3 Answers 3
Depends.
If funct(this.value) does something, and you want that something to happen when the button is clicked, then you need #1.
If funct(this.value) returns a function, and you want that function to be run when the button is clicked, you need #2.
Comments
No. Unsurprisingly, two things which are different are not the same.
button.onclick=funct(this.value);
Here, the call to funct is evaluated immediately.
button.onclick=function(){funct(this.value)};
Here, the call to funct is deferred until the button's onclick handler is invoked.
The key difference here is that in the second case (in my post, the first in yours) you are assigning a new function to onclick, but in the first, you are assigning the result of calling funct.
This also has consequences for the value of this and value at the times they are invoked.
the seconds example calls the function and assign to the onclick handler the result of the function (so funct has to return a function)
The first one calls funct when the button is clicked.
funct? Is there some reason you think those two very different syntax might be the same? What is the basis of your question? Did you see some code that looks just like that which led you to believe they're doing the same thing?