javascript - Why my click event handler is (YES "is") working? -


i know it's bit funny because people ask solution not working, in case it's exact opposite.

i playing around javascript , discovered puzzled me! tried searching online can't find useful of subject.

the problem this: after calling function bar once, onclick event working fine. how possible!?

but when ask type of variable x returns undefined instead of number, normal, because x inside bar.

function bar() {     var p = document.getelementbyid("foo");     p.onclick = showalert;     var x = 5;     alert("bar function called !");   }   bar(); 

can enlighten me happening, detailed explanation appreciated.

full code: (jsfiddle link: https://jsfiddle.net/ge4gj5nw)

<!doctype html> <html>   <head>     <style>       #foo {         border: solid blue 1px;         width: 30%;         padding: 10px;       }     </style>   </head>   <body>     <p id="foo">my event element</p>     <p>click on above element..</p>   </body> </html>  <script>   function bar() {     var p = document.getelementbyid("foo");     p.onclick = showalert;     var x = 5;     alert("bar function called !");   }   bar();   function showalert(event) {     alert("onclick event detected!");   } </script> 

even though p scoped bar function getelementbyid return reference node in dom (which of higher scope). calling p.onclick = showalert; mutating onclick attribute (higher scoped) within function.

after calling function "bar" once, "onclick" event working fine.. how possible?

its possible because invocation of bar mutates higher scoped object.

var global = {specialkey: 'i global scoped'}  function testingfunctionscope() {     global.specialkey = 'not function scoped!';     console.log(global.specialkey); // not function scoped! }  testingfunctionscope();  console.log(global.specialkey); // not function scoped! 

Comments

Popular posts from this blog

ios - MKAnnotationView layer is not of expected type: MKLayer -

ZeroMQ on Windows, with Qt Creator -

unity3d - Unity SceneManager.LoadScene quits application -