访问数组中的对象属性
Accessing object properties within an array
我正在使用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>
相关文章:
- 如何从对象的原型方法访问JavaScript对象属性
- 如何将数组项添加到对象属性中
- 设置嵌套对象属性的更好方法
- JavaScript管理具有重复属性名称的对象属性
- 如何使用element.myobj.prop等具有对象属性的元素
- 如何使用(this)访问Angular 2 http rxjs catch函数中的对象属性
- Es6:能够在设置/更新/删除对象属性时调用自定义方法
- 如何在AngularJS工厂中正确声明对象属性
- 如何使用object.assign()从其他对象引用基本对象属性
- 使用XPath样式访问Javascript JSON对象属性
- 将javascript对象(属性+值)合并到一个对象中
- 数组:使对象属性成为数组键
- 无法从JavaScript中的函数调用对象属性
- Google Closure Advanced |无法识别对象属性|动态属性
- Javascript从匿名函数访问外部对象属性
- 从函数更改对象属性
- 如何从字符串变量访问对象属性
- 从嵌套对象属性中获取排除某个值的最高值
- 在Aurelia computeds中,当设置依赖关系时,如何声明对对象属性的依赖关系
- 传递数量不确定的可能嵌套的对象属性