I was reading the book javascript : The Good Parts
, under The function Statement Versus the function Expression, section B.9. There is a line which says that
function statements are subject to hoisting. This means that regardless of where a function is placed, it is moved to the top of the scope in which it is defined. This relaxes the requirement that functions should be declared before used, which I think leads to sloppiness
so according to this i did a simple experiment as follows:
<html>
<script type="text/javascript">
var x = function(){
alert(s);
var s = function(){
return 'sanmevg';
}
};
</script>
<body>
<button onclick="x();">click here</button>
</body></html>
Now according to this book it clearly states that:
it is moved to the top of the scope in which it is defined. This relaxes the requirement that functions should be declared before used
so this means that when that button is clicked then there should be an alert
saying sanmveg
. but the result was unexpected, it return Undefined
.
My Questions
1) Should i take those statement written by Douglas Crockford
,correct for some special case(if yes then it would be so kind enough to tell me those cases)?
2) Is it reflecting some other meaning?
3) Do i have done something wrong in my experiment?
Thank you for all your answers!