[英]Accessing object properties within an array
I'm working with paper.js and I want to create a method that dynamically alters the color property of each "Ball" object instance once every second. 我正在使用paper.js,我想创建一种方法,每秒动态更改每个“ Ball”对象实例的color属性。 Imagine I have an object:
想象一下我有一个对象:
var Ball = function(point, vector) {
this.point = point;
this.dampen = .6;
this.gravity = 0;
this.bounce = -.6;
var radius = this.radius = 10 * Math.random() + 30;
var ball = new Path.Circle({
radius: radius,
fillColor: palette[Math.floor(Math.random()*palette.length)]
});
this.item = new Group({
children: [ball],
transformContent: false,
position: this.point
});
}
I want to add a new object method to "Ball" via "prototype" like so 我想通过“原型”向“球”添加新的对象方法,如下所示
Ball.prototype = {
recolor: function() {
// do stuff here
}
}
Obviously I need to be able to access the "fillColor" property of the variable "ball", but I'm struggling to find a way to do so, I thought from within the recolor method I would be able to use the following: 显然,我需要能够访问变量“ ball”的“ fillColor”属性,但是我正在努力寻找一种方法,我认为从recolor方法中可以使用以下方法:
this.item.children[i].fillColor
or 要么
this.item.children[i].Path.fillColor
However both return "undefined" so obviously I'm being stupid! 但是,两者都返回“ undefined”,所以显然我很愚蠢! What would be the correct way to setup a prototyped method to change the color of the Ball object every second?
设置原型方法每秒更改Ball对象颜色的正确方法是什么?
I tried your example with little changes and it works for me. 我尝试了一下您的示例,几乎没有更改,它对我有用。 Just guessing your objects.
只是猜测你的对象。
Think its something related to how you have defined Group object. 考虑一下它与您如何定义Group对象有关。 I tried :
我试过了 :
function Group(obj) {
this.children = [];
this.transformContent=false;
this.position=0.0;
$.extend(this, obj);
}
Also you can try this.item.children.push(ball);
您也可以尝试
this.item.children.push(ball);
after you initialise this.item. 在初始化this.item之后。
(function Init(){ function Circle(obj) { this.radius = 0; this.fillColor=0; $.extend(this, obj); } function Group(obj) { this.children = []; this.transformContent=false; this.position=0.0; $.extend(this, obj); } var Ball = function(point, vector) { this.point = point; this.dampen = .6; this.gravity = 0; this.bounce = -.6; var radius = this.radius = 10 * Math.random() + 30; var ball = new Circle({ radius: radius, fillColor: 10 }); this.item = new Group({ children: [ball], transformContent: false, position: point }); } Ball.prototype = { recolor: function() { // do stuff here var f = this.item.children[0].fillColor; console.log("f:"+f) } } var b = new Ball(6,7); b.recolor(); })();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.