How can I pass a parameter to a function without it running right away?

前端 未结 3 543
面向向阳花
面向向阳花 2020-12-03 01:30

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

相关标签:
3条回答
  • 2020-12-03 01:47

    Have showArea return a function that works with the id.

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

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


    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
    }
    

    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.

    0 讨论(0)
  • 2020-12-03 01:50

    Try using bind().

    You could also use bind() that binds the function and allows you to pass parameters to that method, without running the method on initialization.

    google.maps.event.addListener( southEast, 'click', showArea.bind( this, 1 ) );
    

    With bind(), the first parameter is always the context (e.g. this) and any other parameters will be passed to the method itself. So,

    • your first method parameter is passed as the second parameter in bind,
    • your second method parameter is passed as the third parameter in bind,
    • etc.

    Note, I'm not a Javascript expert so not sure if there are any implications with this strategy that I'm overlooking.

    0 讨论(0)
  • 2020-12-03 01:50
    myFunction(msg) {console.log(msg)} // example function
    
    myFunction('hello world') // myFunction called "immediately"
    
    () => myFunction('hello world') // myFunction not called here; returns myFunction
    
    function() { return myFunction('hello world') } // myFunction not called here; returns myFunction
    
    0 讨论(0)
提交回复
热议问题