对象不能更改其自身成员的值

objects unable to change its own member's values

本文关键字:成员 不能 对象      更新时间:2023-09-26

我创建了对象类型a,其中有成员x和y,还有一些函数改变成员的值。我见过在调试器中更改成员。但是所有的成员都没有改变。你能解释一下吗?x和y的行为有什么不同吗?一个是局部变量,另一个是参数。

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

奇怪的是,如果我写一个函数来访问成员,可以获得正确的值。为什么? ?

当您想要修改对象属性时,必须显式地涉及this:

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

在原始代码中,这四个函数中对"x"answers"y"的引用将被解析为外部函数(称为"a"的函数)中的局部变量"x"answers"y"。该"a"函数包括一个名为"y"的参数和一个用于"x"的var声明。