访问数组中的对象属性

Accessing object properties within an array

本文关键字:对象 属性 数组 访问      更新时间:2023-09-26

我正在使用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对象的颜色的正确方法是什么?

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

想想它和您如何定义Group对象有关。我试过了:

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

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

查看小提琴

(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>