簡體   English   中英

為什么我這個Closure的內部函數無法訪問外部函數變量?

[英]Why the inner function of this Closure I did can not access to the outer function variables?

我試圖了解閉包和以下代碼:

 var one = 1, two = 2, three = 3; function bom(one, two, three) { console.log(one, two, three); function b(one) { console.log(`From closure ${one}`); }; b(); }; bom(1, 2, 3);

但是,內部函數無法訪問外部函數變量。

誰能向我解釋為什么?

謝謝。

@Pointy 所說的是正確的,您已經對one變量進行了所謂的變量遮蔽,這意味着您實際上已經覆蓋了對b函數作用域內的外部one變量的引用。 它將引用在其參數列表中定義的局部變量one

盡管如此,這確實不是一個閉包的例子,因為函數定義和調用上下文在同一范圍內。 如果您返回函數b然后稍后執行它,那將是一個更好的閉包示例。 這證明bom作用域存在於b函數作用域的閉包內。

下面是一個例子:

 var one = 1, two = 2, three = 3; function bom (one,two, three){ console.log(one,two,three); return function b(){ console.log(`From closure ${one}`); }; }; let myClosureFn = bom(1, 2, 3 ); myClosureFn();

如果 b 和 bom 沒有名為 one 的參數,則可以使用定義為 var 的參數。

var one = 1,
two = 2,
three  = 3;

function bom (two, three) {  
  console.log(one, two,three);  
  function b  () {
    console.log(`From closure ${one}`);
  };
  b();

};

bom(2, 3 );

輸出是:

1 2 3

從關閉 1

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM