0

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?

asked Jul 6, 2013 at 18:03
2
  • 1
    Are they equivalent? Have you tested them with a function named 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? Commented Jul 6, 2013 at 18:05
  • 2
    In first statement you just assign anonymous function body, in second you call function immediately and then assign returned value of that function Commented Jul 6, 2013 at 18:05

3 Answers 3

4

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.

answered Jul 6, 2013 at 18:07
Sign up to request clarification or add additional context in comments.

Comments

3

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.

answered Jul 6, 2013 at 18:07

1 Comment

...and this is most likely different. And irrespective of the value of this, the value of .value will be evaluated at a different time.
0

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.

answered Jul 6, 2013 at 18:05

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.