关于javascript:Cocos2dJS-This-与-Layer-骚操作

35次阅读

共计 1370 个字符,预计需要花费 4 分钟才能阅读完成。

起因:
想要简化几处反复的代码块,代码形如下图
    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 呢

正文完
 0