1

It's an issue with google chrome version 53.0.2785.101 (64-bit). I tried running a simple html file and it throws the error 'slot.testFun is not a function' when I used the word 'slot'.

<html>
<head>
    <title>TEST</title>
</head>
<body>
    <a href="#" onclick="slot.testFun();">Click Here</a>

    <script type="text/javascript">
        var slot = {
            testFun: function(){
                console.log('clicked');
            }
        }
    </script>
</body>
</html>

There are no conflicts with this variable in our code. It's just the browser, not allowing the variable name in this latest version.

If you use any other name except the word 'slot', it works fine.

Santosh Pradhan
  • 149
  • 1
  • 11

1 Answers1

7

This isn't an ECMAScript issue, it is a DOM issue.

The slot attribute has a corresponding slot property, and onclick attributes do stupid things with with so you are effectively calling this.slot.testFun() because it finds slot (which defaults to being an empty string) before it gets to the right scope.

slot is a new addition to the DOM and support for slot is new in Chrome 53. It does not appear in Chrome 52 and might not have made it even into the latest version of other browsers.

The solution: Avoid intrinsic event attributes. Bind event handlers with DOM instead. That protects you from his clash and future-proofs you from future additions to the DOM.

<a href="#">Click Here</a>

<script type="text/javascript">
    var slot = {
        testFun: function(){
            console.log('clicked');
        }
    }
    document.querySelector("a").addEventListener("click", slot.testFun);
</script>
Community
  • 1
  • 1
Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
  • or use `window.slot.testFun` in on*** attributes :p – Jaromanda X Sep 12 '16 at 14:03
  • 2
    @JaromandaX — That would work too, but is far away from best practise. Globals are best avoided in general. Separation of concerns is generally a good idea. – Quentin Sep 12 '16 at 14:04
  • 1
    but why in latest version of chrome only ? It works fine in latest version of firefox. I am facing this issue after I updated my chrome browser. – Santosh Pradhan Sep 12 '16 at 14:12
  • 2
    @SantoshPradhan Because the `slot` property is quite new and only supported in the latest releases. FF has the same problems with more common property names like `id` or `className` etc – Bergi Sep 12 '16 at 14:16