2014-10-16 23 views
-2

我已經喜歡下面的代碼東西:我應該如何通過函數來​​綁定它?

function foo(){ 
    $('div').each(function(){ 
    //here $(this) refers to selected div 
    }); 
}); 

現在,當我的setInterval調用foo的$(this)不會提及每一個()方法的DIV:

setInterval(function(){ 
    foo(); 
},5000); 

我試着用bind()的:

setInterval(function(){ 
    foo(); 
}.bind(this),5000); //or bind(document.querySelectorAll('div')) 

我錯誤地指的是DIV $(this)真的。我該怎麼辦?


下面是我越來越不確定的證明:

enter image description here

enter image description here

+0

給予好評對付垃圾郵件發送者 – Bobby 2014-10-16 14:48:52

+3

做工精細這裏http://jsfiddle.net/bj1zkx9n/ – Anton 2014-10-16 14:49:38

+1

代碼有語法錯誤。 'foo'不應該用'})'關閉。檢查您的控制檯是否存在錯誤,因爲您的代碼無法正常工作 – Andy 2014-10-16 14:50:29

回答

1

假設你想要的each回調中的代碼可以訪問任何值this具有當打電話時,你的代碼有兩個問題。

首先是你不是bind ing foo本身。該代碼

setInterval(function(){ 
    foo(); 
}.bind(this),5000); 

成功綁定this匿名函數function() { foo(); }。這個匿名函數然後直接調用foo,該函數在非嚴格模式下將this設置爲全局對象windowglobal的調用,如同任何直接函數調用一樣。

您需要在匿名函數的this明確地傳遞給foo調用匿名函數內部與callapply

setInterval(function(){ 
    foo.call(this); 
}.bind(this),5000); 

現在foo有權this,你需要做的是this價值訪問裏面的each回調。爲此,您可以諮詢How to access the correct `this` context inside a callback?,它會指示您將外部this存儲在另一個變量中。您只需存儲this另一個變量中,並使用該變量,而不是this內回調中:

function foo() { 
    var outer_this_from_foo = this; 

    $('.rsContent').each(function(){ 
    //here $(this) refers to selected div 
    //but outer_this_from_foo refers to the `this` value just outside this callback 

    var fI = $('>.img-responsive', outer_this_from_foo); 
    // instead of $('>.img-responsive', this) 

    }); 
}; 
+1

@ C-linkNepal已編輯;你可以使用'call'。用'bind',用'foo.bind(this)()'來做,但這是不必要的資源密集型(而不是慣用的); 'foo.call(this)'會做同樣的事情。 – apsillers 2014-10-16 15:11:23

+0

對不起,但我仍然沒有定義。 – 2014-10-16 15:15:50

+0

這是說:Uncaught TypeError:無法讀取未定義的屬性「調用」 – 2014-10-16 15:19:38

相關問題