2012-04-12 86 views
0

我有一個事件觸發,即使它在我嘗試訪問變量的函數內部,我也得到了Uncaught TypeError: Cannot read property '...' of undefined。所以,讓我們說:訪問「this」從其他函數中輸入JavaScript變量

(function($) { 

    $.fn.main = function() { 

     this.setting = 1; 

     $("#someElement").scroll(function() { 

      console.debug(this.setting); 

     }); 

    } 

})(jQuery); 

我敢肯定它是與時機,但話又說回來,我可能是錯的。我應該複製this並公開嗎?任何人?謝謝。

回答

3

由於this動態獲取其值,所以this的值不能鎖定在閉包中。

嘗試:

var self = this; 

和參考自我。

+0

我喜歡你的簡單,儘管你都說得很對。謝謝。絕對是我的想法。 – 2012-04-12 09:05:25

+0

這正是我所做的 – 2012-04-12 12:04:22

1

只需複製this另一個變量

(function($) { 

    $.fn.main = function() { 

     this.setting = 1; 
     var that = this; 
     $("#someElement").scroll(function() { 

      console.debug(that.setting); 

     }); 

    } 

})(jQuery); 
0
(function($) { 

    $.fn.main = function() { 

     this.setting = 1; // "this" refers to the "$.fn.main" object 

     $("#someElement").scroll(function() { 

      console.debug(this.setting); // "this" refers to the "$('#someElement')" object 

     }); 

    } 

})(jQuery); 

如果你想要使用$.fn.mainthis,你可以存儲變量。下面將工作:

(function($) { 

    $.fn.main = function() { 

     var that = this 

     that.setting = 1; // "this.setting" would also work 

     $("#someElement").scroll(function() { 

      console.debug(that.setting); // You need to reference to the other "this" 

     }); 

    } 

})(jQuery); 
0

this滾動內部方法refereing以滾動方式。該方法必須在ID爲'someElement'的元素的滾動事件上調用。並且綁定對象的作用域丟失。