我已经创建了具有成员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>
奇怪的是,如果我写一个函数来访问成员,可以获得正确的值。 为什么?
局部变量('var'关键字)和赋值参数之间没有区别,但有一个用于对象属性(成员)。 – Bergi 2013-04-25 16:22:01