Functions With Same Names In JavaScript
Solution 1:
One aspect that not many people ever think about with JavaScript is that if you define multiple functions with the same name then the last one defined will be the one that actually runs. JavaScript functions are not polymorphic the way that functions in many other languages are in that JavaScript doesn't care if the actual arguments defined for the functions are different as it can't distinguish between them on that basis. Where in other languages you might have myfunc(oneparm) and myfunc(parmone, parmtwo) as two separate functions with the one that gets run depending on the number of parameters passed, in JavaScript the last one defined will always be the one run regardless of the number of parameters.
Solution 2:
Named functions in javascript are more like variables. If you change the value of a variable, no error occurs, the variable simply has a new value. The same can be said of a function in javascript.
Solution 3:
In JS you can redefine functions. A subsequent function with the same name as another function will overwrite it. (Subject to scope)
Solution 4:
Because it gets overwritten by the latest one.
Solution 5:
JavaScript is highly forgiving in these aspects (like redeclaring a variable or function). The latest one hides or override the previous ones.
In your case, I assume that the js file was loaded after the function Boo
inside the html was parsed. Thus when you click on the button, the definition of Boo
in js file is the only Boo
available.
Post a Comment for "Functions With Same Names In JavaScript"