Hoy Cheung
Hoy Cheung

Reputation: 1670

objects unable to change its own member's values

I have created object type a which has member x and y, also some functions changing the members' value. I have seen the members been changed in debugger. But none of the members are changed. Can you explain? Is there any difference in behaviour of x and y? one is local variable and the other is a parameter.

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

Strangely if i write a function to access the members, the correct values can be obtained. why???

Upvotes: 0

Views: 70

Answers (1)

Pointy
Pointy

Reputation: 413966

You have to explicitly involve this when you want to modify object properties:

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

In your original code, references to "x" and "y" inside those four functions would be resolved to the local variables "x" and "y" inside the outer function (the function called "a"). That "a" function includes a parameter called "y" and a var declaration for "x".

Upvotes: 4

Related Questions