簡體   English   中英

Javascript范圍和局部變量

[英]Javascript Scope and local variables

我真的不確定在Javascript中是否可行。 這是我的功能:

var tree = function(name, callback) {
  if (this.name) {
    this.name.push(name)
    print(this.name)
  } else {
    this.name = []
  }
  callback()
}

我想按以下方式使用它並打印出層次結構:

tree("john", function() {
  tree("geoff", function() {
    tree("peter", function() {
      tree("richard", function() {
      })
    })
  })
  tree("dave", function() {
  })
})

這是所需的輸出:

// ['john']
// ['john', 'geoff']
// ['john', 'geoff', 'peter']
// ['john', 'geoff', 'peter', 'richard']
// ['john', 'dave']

但不幸的是

// ['john', 'geoff', 'peter', 'richard', 'dave']

最后一個函數調用。 有沒有辦法獲得理想的結果?

親切的問候

亞當·格羅夫斯

最后一行打印所有名稱的原因是因為this.names從不刪除要添加到其中的名稱。 您只是在其上附加名稱。 因此,在進行函數調用時

callback()  

具有價值

function() {
  tree("richard", function() {
})  

this.names = ['john','geoff','peter'],並在調用this.names = ['john','geoff','peter','richard']之后 所以現在當你打電話

tree("dave", function() {
});

this.names仍然是['john','geoff','peter','richard']

請嘗試以下操作,注意我將this.name更改為this.names使其更易於閱讀。

var tree = function(name, callback) {
  if (!this.names) {
    this.names = [];
  }
  this.names.push(name);
  print(this.names);
  callback();
  this.names.pop();
}  

我不確定回調函數是做什么的,但是在調用它時可能應該使用apply()或call()。

callback.apply( this, arguments );

暫無
暫無

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

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