var NewYearActivity = cc.Layer.extend({
self:null,
select:null,
ctor:function(){
this._super();
self = this;
},
init:function(){
this.initsomething();
},
initsomething:function(){
self.select = 1; //正常
select = 1; //报错
},
});
求解为什么select 通过this.select 和 self.select都不报错,但是不能直接使用。而且self和select是同级变量,如果select报错,为什么self不报错。实在想不明白。
楼上贴的代码貌似不也不会报错,算了还是贴源代码吧!
var NewYearActivity = cc.Layer.extend({
self:null,
Panel_Layer:null,
selectButton:null,
ctor:function(){
this._super();
self = this;
this.init();
},
init:function(){
if (this._super()) {
var newyear_ui_json = ccs.load(newyear_activity_ui);
var mainLayer = newyear_ui_json.node;
Panel_Layer = mainLayer.getChildByName("Panel_Layer");
this.addChild(mainLayer);
this.initTouch();
return true;
}
return false;
},
initTouch:function(){
//七天按钮
var button_layer = Panel_Layer.getChildByName("buttom_layer");
for (var i = 1; i < 8; i++) {
var daybutton = button_layer.getChildByName("Button_" + i);
daybutton.index = i;
var isGone = false;
//selectButton = daybutton //这样不报错
//判断第i天是否已经过去
///////////////////////////
if (isGone) {
var recieved = new cc.Sprite("activity_newyear/got.png");
daybutton.addChild(recieved);
recieved.setPosition(cc.p(daybutton.width/2,daybutton.height/2));
daybutton.setTouchEnabled(false);
} else {
if (!selectButton) {
selectButton = daybutton;
selectButton.setBrightStyle(ccui.Widget.BRIGHT_STYLE_HIGH_LIGHT);
self.refreshGiftByDay(i);
}
var daybutton_fun = function(sender,event){
selectButton.setBrightStyle(ccui.Widget.BRIGHT_STYLE_NORMAL);
sender.setBrightStyle(ccui.Widget.BRIGHT_STYLE_HIGH_LIGHT);
selectButton = sender;
self.refreshGiftByDay(sender.index);
};
daybutton.addTouchEventListener(daybutton_fun);
}
}
},
refreshGiftByDay:function(index){
},
});
就多了个if else的作用域就报错了,求大神解答
var NewYearActivity = cc.Layer.extend({
self: null,
select: null,
ctor: function() {
this._super();
self = this; // 这个self并非上面定义的self,而是全局变量self。这里把this赋值给了全局变量self。
},
init: function() {
this.initsomething();
},
initsomething: function() {
self.select = 1; //正常 // 这里也是访问的全局变量self,由于之前把this赋值给了它,因此相当于this.select
select = 1; //报错 // 这里访问的是全局变量select
},
});
你需要用this.self和this.select来访问自己定义的变量
1赞
好吧!刚接触js没多久。自以为是的弄了个self,没想到还有个全局self。这里十分感谢了。
楼上正解,不过有一点楼主还是需要注意下,在定义变量的时候不要忘了 var 关键字,不用 var 声明的变量就会自动成为全局变量,更具体的说是成为全局对象(window)的一个属性。楼主贴出的代码中,ctor 函数中声明的变量 self 如果用 var self 的方式声明,就不会出现全局变量的问题