0

メンバー x と y を持つオブジェクト型 a を作成し、メンバーの値を変更するいくつかの関数も作成しました。デバッガーでメンバーが変更されているのを見ました。でもメンバーは変わらない。説明できますか?x と y の動作に違いはありますか? 1 つはローカル変数で、もう 1 つはパラメーターです。

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title></title>
</head>
<body>
    <div id="debug"></div>
    <script src="Scripts/jquery-2.0.0.min.js"></script>
    <script>
        function a(y) {
            var x = 0;
            return {
                x: x,
                y: y,
                getX: getX,
                getY: getY,
                processX: processX,
                processY: processY,
            }
            function getX() {
                return x;
            }
            function getY() {
                return y;
            }
            function processX() {
                this.x = 1;
            }
            function processY() {
                this.y = 100;
            }
        }
        $(function () {
            var objs = [];
            for (var i = 0; i < 3; i++) {
                objs[i] = a(i);
            }
            objs[0].processX();
            objs[1].processY();
            objs.forEach(function (o) {
                $("#debug").append($("<p>").text(o.x + " " + o.y));
                $("#debug").append($("<p>").text(o.getX() + " " + o.getY()));
//result:
//1 0
//0 0
//0 100
//0 1
//0 2
//0 2
            });
        });
    </script>
</body>
</html>

不思議なことにメンバーにアクセスする関数を書くと正しい値が得られる。どうして???

4

1 に答える 1

4

オブジェクトのプロパティを変更する場合は、明示的に関与thisする必要があります。

        function getX() {
            return this.x;
        }
        function getY() {
            return this.y;
        }
        function processX() {
            this.x = 1;
        }
        function processY() {
            this.y = 100;
        }

元のコードでは、これら 4 つの関数内の "x" と "y" への参照は、外側の関数 ("a" という関数) 内のローカル変数 "x" と "y" に解決されます。その「a」関数には、「y」というパラメーターと「varx」の宣言が含まれています。

于 2013-04-25T15:10:59.677 に答える