2017-02-17 54 views
0

嗨我試圖在jQuery中創建一個對象,並且一切正常,但不知何故,我無法通過一些必要的屬性超出setInterval函數BC當我測試它總是彈出「不確定」。這是我的代碼草案。「setInterval」函數是在構造函數中賦值的轉儲屬性

在此先感謝!

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 

    }; 
+1

alert(_this.var2),1000,function(){}應該做什麼? –

回答

1

當您在某個回調函數中使用「this」時,它使用函數作用域「this」。因此,嘗試設置一個「外部這個」:

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 

}; 
+0

嘿整潔的解決方案..謝謝很多人 –

+0

選擇這個答覆接受可以幫助其他人(: –

+0

@MatheusMartins編輯你的答案。它的可怕的風格不關閉函數調用.. –

相關問題