What is lexical scope?

2018-12-31 04:21发布

Could someone please give me a brief introduction to lexical scoping?

13条回答
孤独寂梦人
2楼-- · 2018-12-31 04:58

Lexical scope means that a function looks up variables in the context where it was defined, and not in the scope immediately around it.

Look at how lexical scope works in Lisp if you want more detail. The selected answer by Kyle Cronin in Dynamic and Lexical variables in Common Lisp is a lot clearer than the answers here.

Coincidentally I only learned about this in a Lisp class, and it happens to apply in JS as well.

I ran this code in chrome's console.

// javascript               equivalent Lisp
var x = 5;                //(setf x 5)
console.debug(x);         //(print x)
function print_x(){       //(defun print-x () 
    console.debug(x);     //    (print x)
}                         //)
(function(){              //(let  
    var x = 10;           //    ((x 10))
    console.debug(x);     //    (print x)
    print_x();            //    (print-x)
})();                     //)

output:

5
10
5 
查看更多
登录 后发表回答