簡體   English   中英

在JavaScript上的函數之間傳遞變量

[英]passing variables across functions on javascript

我正在嘗試跨函數傳遞變量,
就像是

 function one() { var x = 1 } function two() { var y = x + 1; } alert(y); 

有辦法嗎?

編輯:感謝大家的幫助,但是也許我應該更具體地回答我的問題。

您將需要通過將變量聲明提取到函數外部來提升作用域。 也就是說,在函數外部定義xy 請注意,您仍然可以從職能范圍內更新它們的 但是,不要忘記,您實際上還需要同時調用這兩個函數!

可以在以下內容中看到:

 var x, y; function one() { x = 1; } function two() { y = x + 1; } one(); two(); console.log(y); 

如果您真的想讓變量在一種方法中聲明,請返回它

  function one(){ var x = 1; return x; } function two() { var x = one(); var y = x + 1; return y; } alert(two()); 

您當前的方式在函數范圍內有x和y,這意味着另一個函數不知道它的存在。 同樣,根據功能命名功能也是一種很好的做法。 3種簡單的方法可以做到這一點。

  1. 全球
  2. PARAMS
  3. 排隊

  1. 在任何功能都可以達到的功能范圍之外設置兩個變量。

 var x, y; function assignOne() { x = 1; } function addOne() { y = x + 1; } assignOne(); addOne(); console.log(y); 

  1. 將參數傳遞給函數並返回值。

 function one() { return 1; } function addOneTo(x) { return x + 1; } const y = addOneTo(one()); console.log(y); 

  1. 內聯執行功能

 var x = null; function one() { x = 1; } function two() { return x + 1; } one(); const y = two(); console.log(y); 

似乎您想在兩個函數之間共享狀態而不是傳遞參數。 因此,面向對象的模式似乎是合適的。

 class Thing { constructor() { this.x = 1; } one() { return this.x; } two() { return this.x + 1; } } const t = new Thing(); console.log(t.one()); console.log(t.two()); 

如果要在函數之間共享變量,但又不想在全局范圍內聲明它們,則可以使用如下所示的閉包:

(function() {
  var x, y;

  function one() {
    var x = 1
  }

  function two() {
    var y = x + 1;
  }
  one();
  two();
  alert(y);
})();

暫無
暫無

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

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