0

我在 JavaScript 中有一些示例代码,如下所示。单击按钮时,始终调用对象xyz的名为doSomething的私有方法,即使在全局级别存在同名方法。我试图了解 JavaScript 级别发生了什么。

问题:在这种情况下,为什么总是调用doSomething的私有方法而不是同名的全局方法?

<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>

4

1 回答 1

0

通过定义doSomethinginside xyz,您将覆盖doSomething范围内的全局xyz

于 2016-12-31T11:13:14.830 回答