我在返回对象属性的值
时遇到问题function Obj() {
this.objects =
[
{
id: 0,
values: {
x: 10,
y: 10
}
},
{
id: 1,
values: {
x: 15,
y: 20
}
}
];
}
Obj.prototype.getOjects = function() {
return this.objects;
};
Obj.prototype.getModifiedOjects = function() {
var i, obj;
obj = this.getOjects();
for(i=0; i<obj.length; i++ ){
obj[i].values.x *= 2;
obj[i].values.y *= 2;
}
return obj;
};
var obj = new Obj(), modifiedObjects;
console.log(obj.getOjects()); // value of 0 => {x => 10, y: 10}, 1 => {x => 15, y: 30}
modifiedObjects = obj.getModifiedOjects(); // Do something with mofified objects
console.log(obj.getOjects()); // value of 0 => {x => 20, y: 20}, 1 => {x => 30, y: 40}
当我调用 getModifiedOjects 函数时,也会更改对象属性的值。
如何使 getOjects 函数不通过引用返回对象属性?
感谢。
答案 0 :(得分:0)
要返回对象的副本而不是您需要创建副本的对象:
Obj.prototype.getModifiedOjects = function() {
var i, obj, result;
obj = this.getOjects();
result = [];
for (i = 0; i < obj.length; i++) {
result.push({
id: obj[i].id,
values: {
x: obj[i].values.x * 2,
y: obj[i].values.y * 2
}
});
}
return result;
};
答案 1 :(得分:0)
Javascript中的对象通过引用传递(如您所见),因此getObjects()
只返回指向obj
内部的同一对象的指针。使getObjects()
返回完全不同的东西的唯一方法是在不改变其中obj
的内容的情况下进行修改,即制作对象的显式副本。
由于您的对象中包含嵌套对象,因此您必须制作一个“深层”副本,以便复制所有内容。
克隆或复制对象有多种不同的方法。以下是一些参考文献:
How do I correctly clone a JavaScript object?
What is the most efficient way to deep clone an object in JavaScript?
答案 2 :(得分:0)
这是我对这个问题的最终解决方案:
function Obj() {
this.objects =
[
{
id: 0,
values: {
x: 10,
y: 10
}
},
{
id: 1,
values: {
x: 15,
y: 20
}
}
];
}
Obj.prototype.getOjects = function() {
return this.objects;
};
Obj.prototype.clone = function(obj) {
if (obj == null || typeof (obj) != 'object')
return obj;
var temp = new obj.constructor();
for (var key in obj)
temp[key] = this.clone(obj[key]);
return temp;
};
Obj.prototype.getModifiedOjects = function() {
var i;
var obj = this.getOjects();
for (i = 0; i < obj.length; i++) {
obj[i].values.x *= 2;
obj[i].values.y *= 2;
}
return obj;
};
var obj = new Obj(), modifiedObjects, cloneOb;
cloneOb = obj.clone(obj);
modifiedObjects = cloneOb.getModifiedOjects(); // Do something with mofified objects
console.log(obj.getOjects()); // value of 0 => {x => 10, y: 10}, 1 => {x => 15, y: 20} - Finaly :)
console.log(modifiedObjects); // value of 0 => {x => 20, y: 20}, 1 => {x => 30, y: 40}