2013-04-25 30 views
0

我已经创建了具有成员x和y的对象类型a,也有一些函数更改成员的值。 我看到成员在调试器中进行了更改。但是没有一个成员改变了。你可以解释吗? 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> 

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

+0

局部变量('var'关键字)和赋值参数之间没有区别,但有一个用于对象属性(成员)。 – Bergi 2013-04-25 16:22:01

回答

4

你必须明确地涉及this当你想修改对象属性:

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

在你的原代码,对“X”和“Y”这四个函数中会被解析为局部变量外部函数中的“x”和“y”(称为“a”的函数)。该“a”功能包括称为“y”的参数和用于“x”的var声明。

+0

所以,如果我不这样做,它会产生一个新的局部变量? 我怎样才能访问这些值? – 2013-04-25 15:16:12

+0

@ user1978421在这种特殊情况下,“processX”函数中的“x”将引用在函数“a”中声明的“x”,并且“processY”中的“y”将引用“y”参数来起作用“一个”。 – Pointy 2013-04-25 19:15:50

+0

其中x和y表示返回块内的x和y? – 2013-04-25 19:18:03