JavaScript - 对象属性不一致

JavaScript - Object property inconsistency

本文关键字:不一致 属性 对象 JavaScript      更新时间:2023-09-26

我遇到了一个问题,我发现很难找到有关我的信息,因为我不知道潜在的问题。我正在尝试在对象内设置一个属性,当我控制台时.log该属性给出了预期的结果,但是当我控制台时.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

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

当您调用时:

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

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

也许这更接近您正在寻找的内容:

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);