这段代码如何(例如以什么顺序)运行以及它的作用是什么?

Joo*_*oon 12 javascript

我发现了这个疯狂的JavaScript代码.

有人可以详细说明这段代码的确切步骤,为什么?

(function a(a){
    return a;
})
(function b(b){
    return b;
})
(function c(c){
    return c;
})
(true);
Run Code Online (Sandbox Code Playgroud)

小智 10

  • 这将自我调用a被给定function b作为参数(因为a被定义为变量a的局部范围,将接管存在功能 a这是在父范围中声明).
  • 然后它会自我调用b哪个c作为参数给出.
  • 最后,函数c是自调用的,它返回true为参数.

您可以将其视为一个链:

a(var a)    // function b given as arg. When a returns b() will be invoked
   b(var b) // function c given as arg. When b returns c() will be invoked
      c(true)
Run Code Online (Sandbox Code Playgroud)

a当函数内部(局部范围)是一个变量,因为function foo(bar){}它是相同的function(){var bar = arguments[0]}.

该函数a可以像这样编写并执行相同的操作:

function a(foo){
    return foo;
}
Run Code Online (Sandbox Code Playgroud)

你可以这样做验证:

console.log('start');

(function a(a){
    console.log('a', typeof a);
    return a;
})
(function b(b){
    console.log('b', typeof b);
    return b;
})
(function c(c){
    console.log('c', typeof c);
    return c;
})
(true);

console.log('end');
Run Code Online (Sandbox Code Playgroud)

在网上直播这里

控制台输出(更新以显示在FF中以及使用Chrome查看功能定义输出):

> start
> a function
> b function
> c boolean
> end
Run Code Online (Sandbox Code Playgroud)