[問題] 請問return function的意義

作者: alair99 (I think home)   2014-08-25 17:08:04
程式碼請參考 http://jsbin.com/sirotikujicu/1/edit?html,output
這個程式主要是用來讓使用者點選google map上的marker之後,
跳出一個infowindow,然後顯示其文字。
其中有一段
google.maps.event.addListener(marker,'click', function(content){
return function() {
infowindow.setContent(content);//set the content
infowindow.open(map,this);
}
}(content));
請問這一段第2行為什麼要用return function ,跟第4行的this有關嗎?
禮拜六參考google大神寫的,
但是現在竟然看不懂了 = =|||
作者: qwer820404 (GB2)   2014-08-25 21:53:00
如果沒搞錯的話 是閉包嗎
作者: Panasonic (ideas for life)   2014-08-25 23:39:00
跟content比較有關,立即執行式餵進去返回一個callback用閉包來作一個wrapper,很常見的方式
作者: s25g5d4 (function(){})()   2014-08-26 00:05:00
是野生的閉包沒錯, 因為事件觸發一定在 for 迴圈結束後若沒有用閉包包起來 那麼 content 永遠是迴圈最後一次的資料, 用閉包包起來才可以保存 content 不被蓋掉至於那個 this 跟閉包無關, 就只是 handler 執行時可能用了 call 或 apply 把 this 改成 marker稍微修改一下就能驗證 this === marker
作者: alair99 (I think home)   2014-08-27 12:09:00
謝謝樓上各位大大,我再找時間研究一下 :)

Links booklink

Contact Us: admin [ a t ] ucptt.com