您好我正在尝试在jQuery中创建一个对象,一切都运行正常但不知何故我无法传递一些必要的属性超出setInterval函数bc当我测试它总是弹出“未定义”。这是我的草案代码。
提前致谢!!
function MyFunction(var1){
this.var = var1;
this.var2 = 2;
this.pause = 3000;
this.slideOn();
}
MyFunction.prototype.slideOn = function(){
alert(this.var); //alerts the value
setInterval(function(){ //doesnt work and it alerts "undefined"
alert(this.var2),1000,function(){}
},this.pause // works again with no hassle
};
答案 0 :(得分:1)
当你使用"这个"在一些回调函数中,它使用了作用域#34;这个"。所以,尝试设置"外部":
function MyFunction(var1){
this.var = var1;
this.var2 = 2;
this.pause = 3000;
this.slideOn();
}
MyFunction.prototype.slideOn = function(){
var _this = this;
alert(_this.var); //alerts the value
setInterval(function(){ //doesnt work and it alerts "undefined"
alert(_this.var2),1000,function(){}; //100 and function are senseless
},_this.pause); // works again with no hassle
};