Jump to content

Javascript Syntax differences


markeizer

Recommended Posts

I'm sorry if, to many of you, this would seem like an obvious question, but I haven't been able to find a satisfying answer yet.

 

Consider this piece of code;

<button onclick="myFunction()">                   Type A<button onclick="function(){myFunction()}">       Type B

The first one calles the function, the second calls a function that, inside it, calles myFunction.

I have notices sometimes type A and B both work, sometimes only one of them works, but I haven't been able to understand why exactly.

 

Also applicable to:

var x = document.getElementById("example")x.onclick=myFunction()var x = document.getElementById("example")x.onclick=function(){myFunction()}

Can someone point out the differences for me? Would be very appreciated, I'm kinda stuck on this.

Thanks in advance.

Edited by markeizer
Link to comment
Share on other sites

it's hard without an actual of something you're trying to implement, but what you have described is accurate in the very general and high level sense of it.

 

As for your second examples, I wouldn't expect those to work at all, since you're setting the event to a string and not an actual function.

Link to comment
Share on other sites

as in they both do what you say they will do (executes a function, executes a function that executes another function), but clearly there is some contextual expectation where you think they should be "working" but they aren't.

Link to comment
Share on other sites

 

 

I have notices sometimes type A and B both work, sometimes only one of them works, but I haven't been able to understand why exactly.

They both "work", in that the function gets executed. The difference between them is that they run in different scopes. The first one will run in the scope of the element that it is defined on, and the second will run in the global window scope.

 

var x = document.getElementById("example")x.onclick=myFunction()var x = document.getElementById("example")x.onclick=function(){myFunction()}

 

The first example will execute myFunction immediately, and assign the return value of that function to the onclick handler. The second example will set an anonymous function which executes myFunction as the click handler. If you just want to execute myFunction when they click on the element all you need to do is this:

 

x.onclick=myFunction

Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
×
×
  • Create New...