[英]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? 如何在此调用中调用initialize函数的参数?
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. 调用1即使没有传递任何参数也可以工作,但这与我要完成的调用2类似。
Sorry, this is probably something quite easy, I'm new to javascript... (but I've googled for quite some time now) 抱歉,这可能很简单,我是javascript的新手...(但是我已经在Google上搜索了一段时间了)
Edit: 编辑:
Grrr, found it, swear I already tried it, must have had a type or smoething! Grrr,找到它了,发誓我已经尝试过了,一定是有类型或平滑的!
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: 不完全是,initialize没有DomListener的签名,最好这样做:
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). 第一个将两个参数推入特殊参数伪数组(因此需要call ),然后在侦听器上下文的上下文中调用initialize, 将当前函数的参数应用于被调用函数的参数(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. 这是其中的原因之一
Function.prototype.bind
可以实现的,记住这this
你想太多,虽然。
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
. 上述将调用
initialised
与this
设定为window
和第一两个参数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"
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.