gpt4 book ai didi

javascript - 对象无法更改其自身成员的值

转载 作者:行者123 更新时间:2023-11-28 16:03:07 25 4
gpt4 key购买 nike

我创建了对象类型 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”和“y”的引用将解析为外部函数(称为“a”的函数)内的局部变量“x”和“y”。该“a”函数包含一个名为“y”的参数和一个“x”的 var 声明。

关于javascript - 对象无法更改其自身成员的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16218425/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com