JavaScript - 对象属性不一致

时间:2015-03-12 00:38:03

标签: javascript object properties

我遇到一个问题,我发现很难找到有关我不知道潜在问题的信息。 我试图在一个对象内部设置一个属性,当我在console.log中时,它给出了预期的结果,但是当我在console.log整个对象时,里面的属性是不同的。

defaults:{
        uid:undefined,      
        createSphere:function(uid,coordinates)
        { 
        this.uid = uid;
        console.log(this.uid);
        console.log(uid);
        console.log(this);
        console.log(this.uid);

我在一个简单的for循环中运行createSphere函数。在这里你可以看到我如何为函数分配uid。

for(i = 0;i<n;i++)
        {
        coordinates = {x:0,y:5,z:0}
        coordinates.x = 0+ (40*Math.sin(Math.PI*(i/2)))
        coordinates.z = 0+ (40*Math.cos(Math.PI*(i/2)))
        spheres.defaults.createSphere((i+1),coordinates);
        }

在这里,您可以在使用第一个块中的代码创建第一个球体时看到生成的日志。 console.logs是在彼此之后直接执行的,因此没有什么能够更改日志记录之间的值。我想将其上传到图像中以便更清晰,但遗憾的是我不能。

1                                         
1                                          
Object
action: function (order,impulseVector){
createSphere: function (uid,coordinates)
  uid: 2
__proto__: Object
1

所以问题是;当直接从属性中获取值时,它与使用整个对象时不同。

2 个答案:

答案 0 :(得分:0)

致电时:

spheres.defaults.createSphere((i+1),coordinates);

它不会创建新的球体对象。相反,它只是更新&#34; spheres.defaults.uid&#34;。

也许这更接近你想要的东西:

&#13;
&#13;
var Sphere = function(uid, coordinates){
  this.uid = uid;
  this.coordinates = coordinates;
  }

var spheres = [];

spheres.push(new Sphere(1, null));
spheres.push(new Sphere(2, null));
spheres.push(new Sphere(3, null));
spheres.push(new Sphere(4, null));

console.log(spheres);
&#13;
&#13;
&#13;

答案 1 :(得分:0)

分配this.uid = uid时,有可能不是以uid的副本形式而是以对该对象的引用形式来分配this.uid。当您更改uid的值时,this.uid的值也会更改。这就解释了为什么其他球共享最后创建的球的uid。

console.log的作用是,当您记录属性时,它立即为您提供了值,但是当您记录对象时,将为您提供一个下拉箭头和{...}

如果在创建新球体之前,即在uid值更改之前,单击“ console.log(this)”的下拉箭头,则该对象的日志实际上与该日志一致财产。

如果在扩展“ this”对象之前等待创建第二个球体(以及uid的值更改),则在uid更改后,控制台将自动向您显示该对象的更新版本。这就是为什么对象和属性看起来不一致的原因。

如果要复制对象,则可以使用Object.assign代替:

this.uid = Object.assign({}, uid);

编辑:就我的情况而言,Object.assign()并没有真正起作用;我必须使用:

this.shallowCopy = JSON.parse(JSON.stringify(source));