2016-11-21 67 views
0

来自Java背景试图从以下代码中理解。JavaScript Closure - 试图理解以下代码

来源: https://medium.freecodecamp.com/lets-learn-javascript-closures-66feb44f6a44#.cbk6c4e9g

对于功能条(C),该行通过参数Ç条(三),因为我没有看到它在这里。

谢谢。

var x = 10; 
function foo(a) { 
    var b = 20; 

    function bar(c) { 
    var d = 30; 
    return boop(x + a + b + c + d); 
    } 

    function boop(e) { 
    return e * -1; 
    } 

    return bar; 
} 

var moar = foo(5); // Closure 
/* 
    The function below executes the function bar which was returned 
    when we executed the function foo in the line above. The function bar 
    invokes boop, at which point bar gets suspended and boop gets push 
    onto the top of the call stack (see the screenshot below) 
*/ 
moar(15); 
+1

如果我理解正确,函数'foo'返回'bar'。这实际上意味着任何对'foo'的调用都会导致对'bar'的调用。所以'var moar = foo(5)'这行就是调用'bar(5)' – haxxxton

+0

@haxxxton OK,这很有道理。谢谢 –

+0

右半边,'foo(5)'确实会返回函数'bar',其中a是5,但它不会调用'bar'。下面的行调用'bar',它被分配到变量moar,参数为15.就像注释所说的那样。 – Wiebe

回答

1

当你的函数调用变种moar的第一条语句= FOO(5)被执行 moar变量将是功能条(C){风险d = 30;返回BOOP(X + A + B + C + d);

检查片断的理解

var x = 10; 
 
function foo(a) { 
 
    var b = 20; 
 

 
    function bar(c) { 
 
    var d = 30; 
 
    return boop(x + a + b + c + d); 
 
    } 
 
    return bar; 
 
} 
 

 
var moor=foo(10); 
 
console.log(moor);

2.After这种说法moar(15),你实际上是通过15条方法

它将执行杆法现在这个函数会返回boop(80),这只会是-80

var x = 10; 
 
function foo(a) { 
 
    var b = 20; 
 

 
    function bar(c) { 
 
    var d = 30; 
 
    return boop(x + a + b + c + d); 
 
    } 
 

 
    function boop(e) { 
 
    return e * -1; 
 
    } 
 

 
    return bar; 
 
} 
 

 
var moar = foo(5) 
 
console.log(moar(15));

希望它可以帮助

1

moar(15)通过15bar它被复制到参数c

// Closure注释是误导性的,因为想到在函数的声明处配置闭包更有用。

实际情况是,当函数对象被实例化时,配置外部词法环境的指针,然后将该指针复制到与所述函数对象的任何调用相关联的执行上下文中。