[英]Difference between codes of lexical scope
我想知道以下兩個代碼塊之間的區別:
function foo() { var a = 'private variable'; return function a(){ console.log(a) } } foo()(); // output: function a(){...}
對比
function foo() { var a = 'private variable'; function a(){}; return () => {console.log(a)} } foo()(); // output: private variable
In the first block of code, based on the hoisting, the function a definition should be hoisted, and then var a = 'private variable'
rewrite the a
, but why the console.log(a)
output the function definition?
在第一種情況下,當您在console.log
中引用a
時,您實際上是在引用 function a
並且它已經隱藏在var = a
上,因此您無權訪問它。
在第二個選項中, function a() {}
實際上移動到var a = 'private variable'
之上,因此代碼如下所示:
function a() {};
var a;
a = 'private variable';
這就是為什么當你調用foo()()
你的var a = 'private variable';
正在遮蔽 function a
,您會在終端中看到private variable
。
這不是關於吊裝。 第一個變體實際上並沒有聲明 function,它只是一個 function表達式(即“lambda”或“閉包”),它沒有在它自己的詞法 Z31A1FD140BE4BEFAEC5D8ZA 中聲明任何內容。 'a' 在該表達式中所做的是分配生成的 function object 的 'name' 屬性,並使其可用於其主體的詞法 Z31A1FD140BE4BEF2D11E121EC9A18A58
例如在節點中:
> const f = function a() {console.log(a);}
undefined
> a
Thrown:
ReferenceError: a is not defined
> f
[Function: a]
> f()
[Function: a]
undefined
另請參閱https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/function
我希望下面的代碼可以幫助您了解正在發生的事情。
當您使用return function a() {... }
它不會被視為function declaration
,但將被視為Variable assignment
,如a = function () {... }; return a;
a = function () {... }; return a;
. 並且return
將在稍后執行a
將值保存為function
。
如下代碼所示,您可以確定要進行分配,直到它到達該行。 所以當我們使用foo(1)();
它輸出private variable
。
function foo(returnString) { var a = 'private variable'; if (returnString) return function() { console.log(a); }; return function a() { console.log(a); }; } foo()(); // output: function a() { console.log(a); } foo(1)(); // output: private variable
在您的第二種情況下,它非常簡單。 按優先順序
function foo() { var a = 'private variable'; function a() {}; return () => { console.log(a); } } foo()(); // output: private variable
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.