JS中变量的作用区间是十分苛刻的
通常你可能以为只要是在一个函数内,变量所指代的内存是一样的,其实不然。在一个函数内,如果该函数内部还有一个函数,那么即使同名的变量,指向的内存都不是同一个,如果想用之前变量的内存,需要通过参数传递,或者其在一级函数内,使用this.指向该函数。
如下所示:
cc.Class({
extends: cc.Component,
properties: {
BG : {
default : null,
type : cc.Node
},
Label : {
default : null,
type : cc.Label
},
OptionTable : {
default : null,
type : cc.Node
},
},
onLoad () {
let windowSize=cc.view.getVisibleSize(); // 获取手机窗口大小
this.node.setPosition (windowSize.width / 7 * 2, -110, 0); // 设置游戏按钮位置
this.BG.opacity = 0;
this.Label.node.color = cc.color (255, 255, 255, 255); // 初始化按钮节点
this.node.on ("touchstart", this.OnTouchStart, this);
this.node.on ("touchcancel", this.OnTouchCancel, this);
this.node.on ("touchend", this.OnTouchEnd, this);
let DISABLE = false;
cc.director.on ("OptionIsClosed", function () {
this.DISABLE = false;
}, this);
},
start () {
},
OnTouchStart () {
cc.log (this.DISABLE);
if (this.DISABLE) {return;} // Option Button is disable
this.BG.opacity = 100;
this.Label.node.color = cc.color (0, 0, 0, 0);
this.OptionTable.setPosition (0, 0); // Let OptionTable Show in View
cc.director.emit ("OptionUsed", "Option is Used which should be placed in center and play animation"); // Tell Option Table : You have been Used
// Option Table is used, Option Button is disable
this.DISABLE = true;
},
OnTouchCancel () {
//if (this.DISABLE) {return;}
this.BG.opacity = 0;
this.Label.node.color = cc.color (255, 255, 255, 255);
},
OnTouchEnd () {
//if (this.DISABLE) {return;}
this.BG.opacity = 0;
this.Label.node.color = cc.color (255, 255, 255, 255);
},
// update (dt) {},
});
这个cocoscreatorJS代码中DISABLE变量的作用域只局限于Onload()函数内部,可以直接使用DISABLE变量名调用,但是到了同一个函数的下级函数或者其他函数中,就需要用this.指向该函数。否则内存空间是不一样的。即使使用时不发生错误,也要明白可能是boolen类型的JS变量初始化值为true,巧合和你所需的类型相符。