私有/公共变量Javascript

时间:2013-09-27 01:59:36

标签: javascript

我正在为googlespreadsheet编写一些脚本。其中一个功能需要获取用户输入。之后,我需要在一些其他函数中使用输入,我在下面显示了一个示例。问题是,每次我需要使用输入时,是否需要调用函数'Setup()'?这意味着多次要求输入,我知道这是愚蠢的。

我该如何解决这个问题?

谢谢!

var setupdone = false;

function Setup(){
  if(!setupdone){
    numofTeams = Browser.inputBox('Confirm the number of Teams');
    var ui = Browser.msgBox('Ensure that the teams are arranged according to lane allocations below', Browser.Buttons.OK_CANCEL);
    setupdone = true;
  }

  var semisraw = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('Secondary Group 1');
  var range = semisraw.getDataRange();
  values = range.getValues();
};

function numofTeamsprint(){
  Setup();
  Browser.msgBox('Setup is Complete!');
};

3 个答案:

答案 0 :(得分:0)

您可以将numofTeams设置为-1,然后只有在numofTeams< 0时才会询问输入,如下所示:

var numofTeams = -1;

function Setup(){
  if (numofTeams < 0) {
    numofTeams = Browser.inputBox('Confirm the number of Teams');
  }
  var ui = Browser.msgBox('Ensure that the teams are arranged according to lane allocations below', Browser.Buttons.OK_CANCEL);
  var semisraw = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('Secondary Group 1');
  var range = semisraw.getDataRange();
  values = range.getValues();
};

function numofTeamsprint(){
  Setup();
  Logger.log(values[0][0]);
};

如果由于某种原因再次需要该输入,只需将其重新设置为-1,然后再运行Setup()

答案 1 :(得分:0)

如果你将变量定义为全局变量(在函数之外),那么你可以测试它们是否已经设置,只是提示它们是否尚未设置。

var setupDone = false;

function setup () {
  if (!setupDone) {
    // do whatever
    setupDone = true;
  }

}

答案 2 :(得分:0)

如果变量附加到global variable对象,任何变量(如人们所称的那样)都称为window

考虑一下这个例子。

var thisIsAGlobalVar = 4;

function method1() {
    var thisIsALocalVar;

    // My Code
    // 1. thisIsALocalVar is available in this function only
    // 2. Its scope would be destroyed as soon as the function itself goes out of scope
    // 3. thisIsAGlobalVar can be access here.

    //Suppose I introduce another variable, without the var keyword, like the one below, inside of a function, the JavaScript interpretter adds it to the window object

    thisAlsoIsAGlobalVar = "Global";

}

function method2 () {

    //My Code
    // 1. thisIsAGlobalVar can be accessed here also

    //Other Code

    //Now that thisAlsoIsAGlobalVar is declared in method1, it has become global and hence can be used here as well
    //Only Pre-condition being method1 should be called firsr

    console.log(thisAlsoIsAGlobalVar); // Would print "Global"

    console.log(thisIsALocalVar); // Would be "undefined"

}

希望这有帮助,欢呼!