簡體   English   中英

閉包函數的狀態何時確定?

[英]When is a closure function's state determined?

我希望 x.gettf() 在下面(在 javascript 控制台,Chrome 中輸入)返回 true。 請解釋發生了什么。 gettf 似乎沒有訪問 tf 的當前值,而是訪問從 foo?

function foo() { 
    var tf=false; 
    function gettf() {return tf;} 
    return {tf:tf, gettf:gettf }
};

x = foo();

{tf: false, gettf: ƒ}

x.tf

false

x.tf = true;

true

x.gettf()

false

x.tf

true

您正在為返回的對象x的屬性tf分配一個新值,而不是修改函數foo聲明的變量。

gettf的作用域是函數foo而不是返回的對象。

此代碼段說明了如何訪問函數foo聲明的變量tf

 function foo() { var tf = 0; function gettf() { return tf; } function settf(nx) { tf = nx; } return { tf: 1, settf: settf, gettf: gettf } } var x = foo(); console.log('tf in returned object: ' + x.tf); console.log('tf in function foo: ' + x.gettf()); x.tf = 2; x.settf(3); console.log('new value of tf in returned object: ' + x.tf); console.log('new value of tf in function foo: ' + x.gettf());
 .as-console-wrapper { max-height: 100% !important; top: 0; }

在您的示例中, foo()返回一個具有兩個屬性“tf”和“gettf”的對象。

聲明x.tf = true; 修改對象的“TF”屬性,但對“TF”變量沒有影響聲明的foo()內。 函數之外的任何東西都無法訪問該變量。

但是,以下方法會起作用:

function foo() { 
  var tf=false; 
  function gettf() {return tf;}
  function settf(x) {tf = x;}
  return {settf:settf, gettf:gettf }
};

暫無
暫無

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

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