gpt4 book ai didi

javascript 对象实例、属性值

转载 作者:行者123 更新时间:2023-11-28 19:48:18 31 4
gpt4 key购买 nike

我创建了一个 DeformableShape 对象并通过 for 循环创建它的实例。我正在调用对象的 setPosition 方法并更改其枢轴属性,但所有实例的值都会更新...假设我有对象 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();
}
}

最佳答案

每次创建 new DeformableShape() 时,您都会覆盖 ds,并且正如下面另一张海报所建议的,您为每个形状使用相同的 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.

关于javascript 对象实例、属性值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23900465/

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