Why is a private method always called when a global method with same name exists in JavaScript?

74 views Asked by At

I have some sample code in JavaScript as below. When the button is clicked then the private method by the name of doSomething of object xyz is always called, even though a method of same name exists at the global level. I am trying to understand what's happening at the JavaScript level.

Question : In this situation, why is the private method of doSomething always getting called rather than the global method of same name?

<script>
    function doSomething() {
        alert('this is a global method available to all');
    }

    var xyz = function() {
        var x = {};
        x.FirstName = "Mike";
        x.changeSeat = function() {
            doSomething();
        }

        function doSomething() {
            alert('this is a private method');
        }

        return x;
    }();
</script>

<button type="button" onclick="xyz.changeSeat();">Private or Global method is called when same name methods exist?</button>

1

There are 1 answers

3
Rudi On

By defining doSomething inside xyz, you overwrite the global doSomething within the scope of xyz