JavaScript 函数作用域和闭包示例:foo 和 bar 函数的调用结果
代码运行结果为:undefined,18,19。
原因是 foo 函数没有返回值,所以第一个 console.log 输出 undefined。而 bar 函数是在 foo 函数内部定义的,所以在全局作用域中无法直接访问,需要先调用 foo 函数才能访问到 bar 函数。
第二个 console.log 调用了 bar 函数,并传入参数 10,此时 x 为 2,y 为 10,num 为 6(因为在 bar 函数中对 num 进行了自增操作),所以输出结果为 18。
第三个 console.log 再次调用 bar 函数,并传入参数 10,此时 x 为 2,y 为 10,num 为 7(因为在第二次调用 bar 函数时,num 已经被自增了 1),所以输出结果为 19。
原文地址: https://www.cveoy.top/t/topic/oIxb 著作权归作者所有。请勿转载和采集!