javascript - objects unable to change its own member's values -
i have created object type has member x , y, functions changing members' value. have seen members been changed in debugger. none of members changed. can explain? there difference in behaviour of x , y? 1 local variable , other 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 = []; (var = 0; < 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 write function access members, correct values can obtained. why???
you have explicitly involve this
when want modify object properties:
function getx() { return this.x; } function gety() { return this.y; } function processx() { this.x = 1; } function processy() { this.y = 100; }
in original code, references "x" , "y" inside 4 functions resolved local variables "x" , "y" inside outer function (the function called "a"). "a" function includes parameter called "y" , var
declaration "x".