Problems with javascript scope in firefox

<div id="myElement2"></div>

<script>
window.onload = function() {
    document.getElementById("myElement1").onclick = function() {
        for (i = 0; i < 2; i++) {
            document.getElementById("myElement2").onmouseover = func;
            function func() {alert("hello"); } } } }
</script>

In chrome and IE, when myElement1 is clicked, func is perfectly tied to myElement2. However, in firefox, when you click myElement1, an error message appears indicating that func is undefined.

I should note that if you make an anonymous function instead of func, then it works in all three browsers.

My question is, how does firefox handle scope in this regard differently for IE and chrome?

Will.

+3
source share
4 answers

I would recommend moving the declaration before assignment and using a variable to store this function, rather than declaring it globally:

<script>
window.onload = function() {
    document.getElementById("myElement1").onclick = function() {
        for (i = 0; i < 2; i++) {
            var func = function() { alert("hello"); }
            document.getElementById("myElement2").onmouseover = func;
        }
    } 
}
</script>
0
source

, , func . JSLint, :

  • . .
  • 'func' , .

, , :

document.getElementById("myElement2").onmouseover = function() {
    alert("hello")
};
+5
+3

, . . , , .

:

<div id="myElement1"></div>
<div id="myElement2"></div>
<script type="text/javascript">

    window.onload = function() {
        document.getElementById("myElement1").onclick = function() {
                document.getElementById("myElement2").onmouseover = myFunctions.func;
         }
     }
    /* Function definitions */ 
    var myFunctions = new Object();
    myFunctions.func = function () {
       alert("hello"); 
    }
</script>
0

Source: https://habr.com/ru/post/1731638/


All Articles