简体   繁体   中英

How to pass a function with arguments, to a function, in javascript

Given this definition...

function initialize(lat, lng)
{
   //do stuff
}

How do I call arguments to the initialize function in this call?

google.maps.event.addDomListener(window, 'load', initialize);

I wanna do something like this:

google.maps.event.addDomListener(window, 'load', initialize(58,18));

Call 1 works even without any arguments passed to it, but it's something similar to call 2 I want to accomplish.

Sorry, this is probably something quite easy, I'm new to javascript... (but I've googled for quite some time now)

Edit:

Grrr, found it, swear I already tried it, must have had a type or smoething!

google.maps.event.addDomListener(window, 'load', function(){initialize(1,2);});
google.maps.event.addDomListener(window, 'load', function () {
    push.call(arguments, 58);
    push.call(arguments, 18);
    initialize.apply(this, arguments);
});

not quite, initialize doesn't have the signature of a DomListener, better to do:

google.maps.event.addDomListener(window, 'load', function () {
    initialize.call(this, 58, 18);
});

the first pushes the two arguments to the special arguments pseudo-array (hence the need for call ) and then invokes initialize in the context of the listener's context, applying the arguments from the current function on the arguments of the called function (initialize).

The second calls initialize in the context of the listener. If you don't need the context, you can simply do:

google.maps.event.addDomListener(window, 'load', function () {
    initialize(58, 18);
});

This is one of the things that Function.prototype.bind can achieve, remember which this you want too, though.

google.maps.event.addDomListener(
    window,
    'load',
    initialize.bind(null, 58, 18)
);

The above will invoke initialised with this set to window and first two params 58 , 18 . It might be easier to understand in this example

function foo(a, b, c) {
    console.log(this, a, b, c);
}
var foobar = foo.bind(null, 1, 2);
foobar('bar');
// window, 1, 2, "bar"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM