簡體   English   中英

函數中的變量范圍

[英]Variable scope in functions

我有一個SCOPE問題。 當我在函數外面聲明“var text”時,一切正常。 但是在函數內部它只在第一部分起作用。 這就是我的意思:

這是一個緩沖功能。 執行緩沖區(“任何東西”)保存“任何東西”。 執行buffer() - 沒有屬性將返回所有屬性。

  • 緩沖液( “AL”)
  • 緩沖液( “EX”)
  • buffer()<=應該返回Alex

但是“文本”的范圍是錯誤的,它不會返回保存的屬性。

  function makeBuffer() { var text = ""; if (arguments.length != 0) { for (let i = 0; i < arguments.length; i++) { console.log(`Adding argument - (${arguments[i]})`); text += arguments[i]; console.log(`New text - (${text})`); } } else { console.log(`text - (${text})`); return text; } } var buffer = makeBuffer; buffer("One", "Two"); document.write(buffer()); 

這是正常的行為。

當范圍消失時,給定范圍中定義的變量就會消失。 每次調用函數都會創建一個新的范圍。

在函數外聲明變量是在它的調用之間共享值的標准方法。

你想要的是工廠:

 function makeBuffer() { var text = ""; return function buffer() { if (arguments.length != 0) { for (let i = 0; i < arguments.length; i++) { console.log(`Adding argument - (${arguments[i]})`); text += arguments[i]; console.log(`New text - (${text})`); } } else { console.log(`text - (${text})`); return text; } } } var buffer = makeBuffer(); buffer("One", "Two"); document.write(buffer()); 

你可以使用一個對象來做到這一點。 這將使您的代碼更有條理。

 var Buffer = function() { this.text = ""; } Buffer.prototype.append = function() { for (var i = 0; i < arguments.length; i++) { this.text += arguments[i]; } } Buffer.prototype.get = function() { return this.text; } var buffer = new Buffer(); buffer.append("One", "Two"); document.write(buffer.get()); 

使用ES6語法更加甜蜜:

 class Buffer { constructor() { this.text = ""; } append() { this.text = this.text.concat(...arguments); } get() { return this.text; } } var buffer = new Buffer(); buffer.append("One", "Two"); document.write(buffer.get()); 

正如昆汀在他的回答中正確指出的那樣,這是一種正常的行為。

不向外部聲明變量的情況下保持函數值的另一種選擇是范圍是將其作為屬性添加到函數本身。

與在JavaScript中一樣,函數是第一類對象,您可以將這些數據直接放入函數對象(就像在任何其他對象中一樣)。

下面的示例請注意如何從函數中獲取屬性textbuffer.text )。

 function makeBuffer() { makeBuffer.text = ""; if (arguments.length != 0) { for (let i = 0; i < arguments.length; i++) { console.log(`Adding argument - (${arguments[i]})`); makeBuffer.text += arguments[i]; console.log(`New text - (${makeBuffer.text})`); } } else { console.log(`text - (${makeBuffer.text})`); return makeBuffer.text; } } var buffer = makeBuffer; buffer("Al", "ex"); console.log(`buffer.text - (${buffer.text})`); 

或者考慮使用閉包來保持函數調用之間的文本值。

閉包是指獨立(自由)變量的函數(在本地使用但在封閉范圍內定義的變量)。 換句話說,這些函數“記住”它們的創建環境。 更多信息在這里

 let makeBuffer = function() { // closure let text = ""; return function() { if (arguments.length != 0) { for (let i = 0; i < arguments.length; i++) { console.log(`Adding argument - (${arguments[i]})`); text += arguments[i]; console.log(`New text - (${text})`); } } else { console.log(`text - (${text})`); return text; } } }; var buffer = makeBuffer(); buffer("Al", "ex"); 

暫無
暫無

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

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