避免全局变量?

时间:2015-07-30 12:39:56

标签: javascript google-sheets global-variables sidebar google-spreadsheet-api

这段代码完全符合我的需要,但我怎么能避免使用全局变量?

全球变量' xxbtnDataxx'在 btnText()中声明。

/**
* Run initializations on sidebar load.
*/

$(function() {
// Assign handler functions to sidebar elements here, if needed.
$(document).on('click', '.qsbutton',function(){
var clickedID = this.value;
btnAction(clickedID);
});

// Call the server here to retrieve any information needed to build
// the dialog, if necessary.
google.script.run.withSuccessHandler(btnText).getBtnData();

});

function btnText(value) {
var btnData = value
xxbtnDataxx = value
var selector = '#quick-shift-button'
for (var i=0,j=btnData.length; i<j;i++) {
      $(selector+i).text(btnData[i][0]);   
  }
}

function btnAction(id) {
var start = xxbtnDataxx[id][1];
var finish = xxbtnDataxx[id][2];
var shift = [[start,finish]];
google.script.run.setShift(shift);
}    
</script> 

2 个答案:

答案 0 :(得分:0)

保持简单:

`a = 0`

上面的代码给出了一个全局范围变量

`var a = 0;`

此代码将提供一个在当前范围内使用的变量,并在其下

`window.a = 0;`

这通常与全局变量相同。

修改 全局在文件中?

xxbtnDataxx = value;//on top

/**
* Run initializations on sidebar load.
*/

$(function() {
// Assign handler functions to sidebar elements here, if needed.
$(document).on('click', '.qsbutton',function(){
var clickedID = this.value;
btnAction(clickedID);
});

// Call the server here to retrieve any information needed to build
// the dialog, if necessary.
google.script.run.withSuccessHandler(btnText).getBtnData();

});

function btnText(value) {
var btnData = value;
var selector = '#quick-shift-button'
for (var i=0,j=btnData.length; i<j;i++) {
      $(selector+i).text(btnData[i][0]);   
  }
}

function btnAction(id) {
var start = xxbtnDataxx[id][1];
var finish = xxbtnDataxx[id][2];
var shift = [[start,finish]];
google.script.run.setShift(shift);
}    
</script> 

答案 1 :(得分:0)

避免我发现有用的全局变量的一种方法是将所有函数包装到&#34;类&#34;中。通过这种方式,您可以调整变量范围&#34;全局&#34;只在你班上。

更新

var Handler = function(){

var xxbtnDataxx = false;
var self = this;

this.init = function(){

    // Assign handler functions to sidebar elements here, if needed.
    $(document).on('click', '.qsbutton',function(){
        var clickedID = this.value;
        self.btnAction(clickedID);
    });

    // Call the server here to retrieve any information needed to build
    // the dialog, if necessary.
    google.script.run.withSuccessHandler(self.btnText).getBtnData();
};

this.btnAction = function (id) {
    var start = xxbtnDataxx[id][1];
    var finish = xxbtnDataxx[id][2];
    var shift = [[start,finish]];
    google.script.run.setShift(shift);
};

this.btnText = function (value) {
    var btnData = value;
    xxbtnDataxx = value;
    var selector = '#quick-shift-button';
    for (var i=0,j=btnData.length; i<j;i++) {
          $(selector+i).text(btnData[i][0]);   
    }
}
};

// Create an instance of the object
var handler = new Handler();

$(function() {
    // Call the init method on the class. Kinda 'ctor'
    handler.init();
});