如何将参数传递给函数而不立即运行? [英] How can I pass a parameter to a function without it running right away?

查看:44
本文介绍了如何将参数传递给函数而不立即运行?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在尝试拼凑一个有点动态的 Google 地图显示时遇到了一些奇怪的问题.我在地图上有叠加层,我想在点击时调用一个函数.最初我对所有东西都进行了硬编码,所以我为每个叠加层设置了一个函数,如下所示:

I'm having somewhat of an odd issue with trying to piece together a somewhat dynamic Google Maps display. I have overlays on a map that I would like to call a function when clicked. Initially I had everything hard coded, so I had a function for each overlay like this:

google.maps.event.addListener(southEast, 'click', showSouth);
function showSouth() {
   // do stuff
}

这没有问题,但后来我让整个页面更加动态,所以我决定制作一个函数来传递一个 ID 然后基于它显示,这就是我觉得它本来应该被设置的方式.我把代码改成这样:

This worked without a problem, but then I made the whole page more dynamic so I decided to make one function that would pass an ID and then display based on that, which is how I feel it should have been set up originally anyway. I altered the code to look more like this:

google.maps.event.addListener(southEast, 'click', showArea(1));
function showArea(id) {
   // do stuff based on that id
}

该函数有效,但问题是它在页面加载时立即被调用.经过研究,我了解到当你调用一个带括号的函数时,该函数会立即被调用,然后它的返回值被引用.来源

The function worked, but the problem is it gets called immediately on page load. After researching I've learned that when you call a function with the parentheses, that function gets called immediately and then it's return value is referenced. source

所以现在我有点不知道如何将 ID 传递给函数而不让它立即调用函数.我找到了一些可行的方法,但我觉得这不应该是我必须一起破解的东西...

So now I'm a little stuck as to how exactly to go about passing that ID to the function without having it call the function immediately. I've found some hacky ways of doing it that might work, but I feel like this shouldn't be something I have to hack together...

推荐答案

showArea 返回一个使用 id 的函数.

Have showArea return a function that works with the id.

function showArea(id) {
   return function() {
       // do stuff with id
   };
}

返回的函数在 id 上关闭,因此它继续引用它,并传递给 addListener 用作处理程序.

The returned function closes over id so it continues to reference it, and is passed to addListener to be used as the handler.

或者,您可以内联调用 showArea(1)...

Alternately, you could just inline the function that calls showArea(1)...

google.maps.event.addListener(southEast, 'click', function() { showArea(1); });
function showArea(id) {
   // do stuff based on that id
}

这会起作用,因为您对 1 进行了硬编码.如果它是一个可以改变的变量,比如在循环中,你会使用第一个例子.

This will work because you're hardcoding the 1. If it was a variable that could change, like in a loop, you'd use the first example.

这篇关于如何将参数传递给函数而不立即运行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆