首页 > 解决方案 > Efficient Javascript Code: better to pass variables as arguments in a function, or to replicate the variables?

问题描述

I want to run function B after function A, but use some variables from function A when I run it. Let's say for the sake of this exercise that I don't want to declare global variables.

Would it be "better" code to write those variables in both functions (scenario A), or to have local variables in function A and pass them as arguments to function B (scenario B)?

Here's a representation of those two scenarios:

Scenario A

function A() {
    var ss = SpreadsheetApp.getActiveSpreadsheet();
    var sheet = ss.getActiveSheet();
    var cell = sheet.getCurrentCell();

    cell.setValue("Hello World");

}

function B(cell) {
    var ss = SpreadsheetApp.getActiveSpreadsheet();
    var sheet = ss.getActiveSheet();
    var cell = sheet.getCurrentCell();
    var txt = "New Text";

    cell.setValue(txt);
}

Scenario B

function A() {
    var ss = SpreadsheetApp.getActiveSpreadsheet();
    var sheet = ss.getActiveSheet();
    var cell = sheet.getCurrentCell();
    cell.setValue("Hello World");

    B(cell);
}

function B(cell) {
    var txt = "New Text";
    cell.setValue(txt);
}

In a recent project I've been working on, I have dozens of variables and scenario B seems "cleaner" cleaner to me, but I really don't know if I should be doing that.

I know this is basic, but I'm still rather new to coding in JavaScript and I can't get my head around this. Any help would be appreciated!

The code above is in Google Apps Script btw.

Thank you :)

标签: javascriptvariablesgoogle-apps-scriptparameter-passing

解决方案


A and B are not the same function. B is a parameterized function. So, logic should be like if we already have the cell value, then call B and if we don't have the cell then call A.

Now, to your question yes, option B is more appealable as as it let you avoid code repetition. But I don't see the purpose of calling B from A in this scenario.

In my opinion, it would be much better if you write a separate function to get the cell so, that the code abide by one function one purpose(SRP).

Below is the working snippet:

 //a function that return default cell value if called
 function GetCell(){
    let ss = SpreadsheetApp.getActiveSpreadsheet();
    let sheet = ss.getActiveSheet();
    return sheet.getCurrentCell();    
  }

 function A() {
    let cell=GetCell(); //get cell value by calling function
    cell.setValue("Hello World");
 } 


//function B execute successfully with parameter or without parameter. 
 function B(cell) {

   if(typeof cell == "undefined") {
    cell=GetCell();
   }
   let txt = "New Text";
   cell.setValue(txt);
 }

推荐阅读