Cocos2d-JS This 与 Layer 骚操作
Posted Hantme
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Cocos2d-JS This 与 Layer 骚操作相关的知识,希望对你有一定的参考价值。
起因:
想要简化几处重复的代码块,代码形如下图
var xxxList = data.xxxList;
if (!this.aaaLayer) {
this.aaaLayer = new AAALayer(xxxList);
this.aaaLayer.setAnchorPoint(0.5, 0.5);
this.background.addChild(this.aaaLayer, 3);
} else {
this.aaaLayer.remove();
this.aaaLayer.layout(xxxList);
}
if (!this.bbbLayer) {
this.bbbLayer = new BBBLayer(xxxList);
this.bbbLayer.setAnchorPoint(0.5, 0.5);
this.background.addChild(this.bbbLayer, 3);
} else {
this.bbbLayer.remove();
this.bbbLayer.layout(xxxList);
}
if (!this.cccLayer) {
this.cccLayer = new CCCLayer(xxxList);
this.cccLayer.setAnchorPoint(0.5, 0.5);
this.background.addChild(this.cccLayer, 3);
} else {
this.cccLayer.remove();
this.cccLayer.layout(xxxList);
}
if (!this.dddLayer) {
this.dddLayer = new DDDLayer(xxxList);
this.dddLayer.setAnchorPoint(0.5, 0.5);
this.background.addChild(this.dddLayer, 3);
} else {
this.dddLayer.remove();
this.dddLayer.layout(xxxList);
}
由于重复度太高,看着实在难受,于是就想整合在一起,但是由于每个Layer都要对应一个构造Layer,通常会需要用条件判断来进行划分,但是这样以来难免又写的很长,所以我决定用两个数组分别存放目标Layer和构造器Layer,于是就有了下面的整合函数:
compressFunc: function (xxxList) {
var targetLayer = [
"aaaLayer",
"bbbLayer",
"cccLayer",
"dddLayer"
];
var constructLayer = [
AAALayer,
BBBLayer,
CCCLayer,
DDDLayer
];
targetLayer.forEach(function (item, index){
this[item] = new constructLayer[index](xxxList[index].data);
this[item].setAnchorPoint(0.5, 0.5);
this.background.addChild(this[item], 3);
}.bind(this));
},
如此一来就可以完美的用forEach和this[item]来避免很长的条件判断了,鉴于平时我都不会用到this[xxx]这种结构,所以姑且记录下来,万一以后就变成了一个Bug呢
以上是关于Cocos2d-JS This 与 Layer 骚操作的主要内容,如果未能解决你的问题,请参考以下文章
卷积骚操作-PSConv:Squeezing Feature Pyramid into One Compact Poly-Scale Convolutional Layer