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>
By defining
doSomething
insidexyz
, you overwrite the globaldoSomething
within the scope ofxyz