JavaScript 变量的作用区间

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,巧合和你所需的类型相符。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值