javascript对象实例,属性值

时间:2014-05-27 23:17:58

标签: javascript

我创建了一个DeformableShape对象并通过for循环创建它的实例。我正在调用object的setPosition方法并更改其pivot属性,但是为所有实例更新了值...说我有对象A而我更改它的枢轴B对象的轴也在改变。以下代码有什么问题?

function DeformableShape(pivot, maxRadius, numSegment){
            this.pivot = pivot;
            this.maxRadius = maxRadius;
            this.numSegment = numSegment;
            this.path = new Path({
                fillColor : 'black',
                fullySelected: false,
                closed:true
            });

            this.path.add(this.pivot)
            for (var i = 0; i < this.numSegment + 1; i++) {
                k = (i == 0) ? 0 : Math.random();
                var delta = new Point({
                    length: (maxRadius * 0.5) + (k * 10 * 0.5),
                    angle: (90 / this.numSegment) * i * -1
                });

                this.path.add({ x:delta.x + this.pivot.x , y:delta.y + this.pivot.y });

            }



        }

        DeformableShape.prototype = {
            iterate: function() {

            },

            setPosition:function(inX){

                this.pivot.x += inX;
                this.path.position.x = this.pivot.x;


            },

            collapse: function(){
                var segments = this.path.segments;
                var i = 5;
                for (var i = 0; i < this.numSegment + 2; i ++){
                    var tween = new TWEEN.Tween( segments[i].point )
                    .to( { x: this.pivot.x , y:this.pivot.y }, 2000 )
                    .easing( TWEEN.Easing.Circular.InOut )

                     tween.delay(Math.ceil(Math.random() * 300));
                     tween.start();
                }   
            }

        }


        // CREATE INSTANCES
        createDeformableShapes = function(){
            var center = new Point(400, 230)
            for(var i=0; i < 5; i++){
                ds = new DeformableShape(center, 40, 5 );
                ds.setPosition(30)
                ds.collapse();
            }
        }

2 个答案:

答案 0 :(得分:2)

每次创建ds时都会覆盖new DeformableShape(),而下面的另一张海报建议您为每个形状使用相同的Point对象。请注意,ds也是全球性的。如果要循环并创建对象,请将它们存储在数组中。

// CREATE INSTANCES
var createDeformableShapes = function(){
    var deformableShapes = [];
    for(var i=0; i < 5; i++){
            var center = new Point(400, 230)
        var ds = new DeformableShape(center, 40, 5 );
        ds.setPosition(30)
        ds.collapse();
        deformableShapes.push(ds);
    }
            return deformableShapes;
}
    // now you have an array of DeformableShapes in createDeformableShapes.

答案 1 :(得分:1)

我尝试了你的代码并稍微玩了一下。问题是你为所有这些对象设置了相同的Point对象,每个对象都正确地引用了该对象(但仍然是同一个对象)。因此,当您将其更改为一个时,您可以更改它。

解决方案是为每个创建一个新的Point对象作为枢轴:)只需在循环中创建中心Point init:

 createDeformableShapes = function(){
        for(var i=0; i < 5; i++){
            var center = new Point(400, 230); //here
            ds = new DeformableShape(center, 40, 5 );
            ds.setPosition(30)
            ds.collapse();
        }
    }
相关问题