2013-06-27 46 views
1

我確信之前已經詢問過這個問題,但我不知道要搜索什麼。具有範圍問題的匿名函數調用

所以我想用一個與被點擊的項目對應的字符串來調用函數,但是我想簡單地將任何新項目添加到一個字符串數組中。

var menuList = ["overview", "help", "search"]; 
var functionCalls = [ 
    function() { toggleMenu(menuList[0]); }, 
    function() { toggleMenu(menuList[1]); }, 
    function() { toggleMenu(menuList[2]); }, 
]; 

所使用這樣一個循環:$("something").click(functionCalls[i])

這就是我想要做(但顯然它不工作):

for (var i in menuList) { 

    // This does not work because the closure references 'i' 
    // which, at the end, is always the index of the last element 
    $("something").click(function() { 
    toggleMenu(menuList[i]); 
    }); 

    // this works, but I have to define each closure 
    $("something").click(functionCalls[i]); 
} 

我怎麼能創建一個匿名函數接受基於變量的值 - 但不保留對變量的引用?

+1

請勿使用'for ... in'來遍歷JavaScript中的數組。改爲使用索引變量和簡單的'for'循環。 – Pointy

+0

這個問題有很多很多重複。這是JavaScript中非常常見的陷阱。 – Pointy

+0

這就是爲什麼我注意到,我確信它之前已被問到。我只是不熟悉JS知道如何正確處理它,或者搜索什麼。 – tsjnsn

回答

3

你可以使用像這樣的IIFE:

for (var i=0; i<menuList.length; i++) { 
    !function(index) { 
    $("something").click(function() { 
     toggleMenu(menuList[index]); 
    }); 
    }(i); 
} 

通過調用匿名函數,您創建當前價值爲i本地副本名爲index。因此,所有處理程序都會收到它們各自的版本i

+0

這就是我正在尋找的東西。謝謝! – tsjnsn