Could somebody please explain or link to a resource that will tell me why :
<script type=" type="text/javascript">
if(typeof window.myfunc == "function"){
alert("Why does myfunc already exist ?");
}
function myfunc(){
}
</script>
will pop up an alert while the myfunc function has not been defined yet ?
I think I found an issue in Chrome, Safari and IE (not FF) which is linked to this behavior. It keeps me from extending the prototype of a function when the js file that contains the function is included more than once in a web page. I’d like to know more about this before calling it a bug and reporting it.
Thank you !
Named function declarations, including the function body, get hoisted to the
top of the scope in JavaScript. I’d recommend reading this article about
JavaScript scoping and
hoisting.
If you did something like this, where you assigned the function to a named
variable, only the variable declaration would be hoisted, but it wouldn’t have
a value until the assignment actually took place:
The above effectively gets treated as: