javascript函数后括号中的参数

问题描述 投票:1回答:3

我在堆栈溢出时找到了谷歌地图标记的解决方案。链接在这里。 Google Maps API Multiple Markers with Infowindows

google.maps.event.addListener(marker,'click', (function(marker,content,infowindow){ 
return function() {
    infowindow.setContent(content);
    infowindow.open(map,marker);
};
})(marker,content,infowindow)); 

我的问题是:(标记,内容,信息窗口)放在javascript函数后面的目的是什么?它叫什么?非常感谢您的进步。

javascript
3个回答
1
投票

它是一个IIFE(立即调用函数表达式),第二个括号调用函数并允许您将参数传递给函数

(function () {
    //statements
})();

检查文档here


1
投票

这是一个自调用函数 - 这意味着在声明之后立即使用这些参数调用它


1
投票

请查看Damian的正式名称答案。

但是,这只是执行通过执行第一个函数创建的函数。

如果我们将代码分解成多行,可能会更有意义:

const makeAFuction = function(marker,content,infowindow){ 
  return function() {
    infowindow.setContent(content);
    infowindow.open(map,marker);
  };
}
const listener = makeAFunction(marker,content,infowindow);
google.maps.event.addListener(marker,'click', listener); 
© www.soinside.com 2019 - 2024. All rights reserved.