2013-08-25 28 views
0

更新#1
我忘了傳遞當前對象作爲第一paremeter;看到K的回答試圖`調用`三種方法,但不能正常工作與jQuery地圖


我有以下方法在谷歌地圖上。該方法做工精細是這樣的:

arc.pLocations(ne, sw,m); 
arc.pLikedLocations(ne, sw, m); 
arc.pLikedItems(ne, sw, m); 

不過,我想有他們這樣,我可以subsequetnly調用數組,但是這是不工作(我會是第一個承認這是一個我的問題):

var selected_methods=[arc.pLocations,arc.pLikedLocations,arc.pLikedItems]; 

// Uncaught TypeError: Object #<Ri> has no method 'lng' - this is for a variable called sw in pLikedLocations 
$.map(selected_methods, function(val, i){ 
    console.log("here is index:" + i); 
    val.call(ne,sw,m); 
}); 

試圖用另一種方式停止包裝這個但這也不能正常工作

$.map(selected_methods, (function(val, i){ 
    console.log("here is index:" + i); 
    val.call(ne,sw,m); 
})(val,i)); // Uncaught ReferenceError: val is not defined on this line! 

我有以下的,我做的事情很簡單的錯誤。任何人都可以發現問題並幫助我嗎?這是星期六晚上,我想要做到這一點。

THX提前

+1

我回避這個問題,但爲什麼你使用'map'?只有當您希望將結果作爲數組返回時才需要,並且不存儲映射的結果。如果你使用'each',你會得到同樣的問題:'$ .each(selected_methods,function(){this.call(arc,ne,sw,m)});'? –

+1

@ScottMermelstein:是的,他們會錯誤地使用['call'](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/call)。 –

+0

啊,這個傢伙 - 我的錯。 – timpone

回答

2

你傳遞了​​錯誤的上下文的call功能。其實,你想念它。試試這個:

var selected_methods=[arc.pLocations,arc.pLikedLocations,arc.pLikedItems]; 

$.map(selected_methods, function(val, i){ 
    console.log("here is index:" + i); 
    val.call(arc,ne,sw,m); //Notice the arc 
}); 
+0

thx可汗需要等待幾分鐘 – timpone

+1

如果你只有'names'中的方法名稱,你也可以''.each(names,function(m){arc [m](ne,sw,m)})''或者你可以''.each(selected_methods,function(f){f(ne,se,m)})'如果這些方法真的只是不關心這個''是什麼的函數。 –

+0

thx @ muistooshort這也工作了,我不得不在每個索引中添加一個值,'each'的值不確定這是否是jQuery 2.0的行爲http://api.jquery.com/jQuery.each/;雖然它像紅寶石,但thx的答案,因爲這是我一起去的。非常感謝 – timpone