简体   繁体   English

javascript,奇怪的功能安排,不明白

[英]javascript, strange function arrangement, don't understand

See the below javascript. 请参阅以下javascript。 When functions are arrangment this way, how is it that they are able to run without being called specifically. 当函数以这种方式排列时,它们如何能够运行而不被专门调用。 What I mean is that the function below runs without being called and I don't understand how. 我的意思是下面的函数在不被调用的情况下运行,而且我不知道该怎么做。

(j, function() {
alert(1);
})

it is eval'd like this: 大概是这样的:

eval(s)(j, function() { catch (_) { } } 

It looks like those are the arguments to a function call, ie 看起来这些是函数调用的参数,即

foo(j, function() {
   alert(1);
})

That will pass the current value of j as the first argument, and the function listed there as the second argument. 这将传递j的当前值作为第一个参数,并在那里列出的函数作为第二个参数。

That said, in order for that function—the one that alerts 1—to be called, foo would have to manually call it. 就是说,要调用该功能(警告1的功能), foo必须手动调用它。 Something along the lines of 遵循以下原则

function foo(j, f){
    f();
}

EDIT 编辑

So, per your question edit, it looks like what's above is more of less correct, except instead of referencing the function directly, you're fetching it from an eval statement. 因此,根据您的问题编辑,上面的内容看起来不太正确,除了您不是从直接引用函数而是从eval语句中获取函数。

Something like this: 像这样:

function foo(j, f){
     f();
}
var s = "foo";
var j = 0;
eval(s)(j, function() {
    alert(1);
})

Here's a working FIDDLE 这是一个工作场所

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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