Julien Kronegg
Julien Kronegg

Reputation: 5251

Conflicting Javascript variable name in Chrome 61.0.3163.79

My Chrome Browser has recently been updated to version 61.0.3163.79 and I noticed a strange behavior with the following Javascript code:

<!doctype html>
<html lang="fr">
    <head>
        <script>
            var scroll = {
                myFunction : function() {console.log('myFunction called');}
            }
        
            scroll.myFunction(); /* first call */
            window.scroll.myFunction(); /* second call */
        </script>
    </head>
    <body>
        <button onclick="scroll.myFunction()">test1</button> <!-- third call -->
        <button onclick="window.scroll.myFunction()">test2</button> <!-- fourth call -->
    </body>
</html>

This code overwrites the window.scroll function (don't ask me why, that's legacy code). The result in console is the following when run and when the "test1" and "test2" buttons are clicked:

myFunction called
myFunction called
Uncaught TypeError: scroll.myFunction is not a function at HTMLButtonElement.onclick
myFunction called

In earlier Chrome version, and in MSIE 11, the function call worked properly when clicking the "test1" and "test2" buttons, resulting in the following messages in the console:

myFunction called
myFunction called
myFunction called
myFunction called

Now the questions:

Note that in the meantime, I changed the variable name to avoid name conflict with the browser native features.

Upvotes: 3

Views: 81

Answers (1)

Keith
Keith

Reputation: 24231

<button onclick="scroll.myFunction()">test1</button>

The problem here is that the scroll your after is on the window object,.

It would appear in recent versions of Chrome they have added a scroll method to the actual button. So what you end up calling is button.scroll.myFunction, rather than window.scroll.myFunction.

Browser vendors could add any named method at any time, so even if you created a global called myScroll, in theory there is nothing stopping the browser vendor adding a myScroll to the button element. Obviously it's unlikely they would, but something to be aware off.

The best way to avoid these sort of issues, is to always have control of your scope, never rely on globals, unless these globals are passed into a scope,. Javascript closures really help here. Unfortunately in your example you have used HTML event binding, rather than code binding so makes this not possible.

Upvotes: 1

Related Questions