访问数组中的对象属性

时间:2014-10-27 17:37:05

标签: javascript arrays object methods

我正在使用paper.js,我想创建一个方法,每秒动态地改变每个“Ball”对象实例的颜色属性。想象一下,我有一个对象:

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

我想通过“原型”像“

”一样向“Ball”添加一个新的对象方法
Ball.prototype = {
    recolor: function() {
        // do stuff here
    }
}

显然我需要能够访问变量“ball”的“fillColor”属性,但我很难找到一种方法这样做,我想在重新着色方法中我可以使用以下内容:

this.item.children[i].fillColor 

this.item.children[i].Path.fillColor 

然而两者都返回“未定义”,所以显然我是愚蠢的!设置原型方法每秒更改Ball对象颜色的正确方法是什么?

1 个答案:

答案 0 :(得分:0)

我尝试了一些改动的例子,它对我有用。只是猜测你的对象。

认为它与您如何定义Group对象有关。我试过了:

function Group(obj) {
        this.children = [];
        this.transformContent=false;
        this.position=0.0;
       $.extend(this, obj);
   }

此外,您可以在初始化this.item后尝试this.item.children.push(ball);

请参阅fiddle



(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>
&#13;
&#13;
&#13;