javascript - 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 :)
解决方案
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);
}
推荐阅读
- javascript - 在 JS 中将 JSON 转为 Map
- python - Python中对全局变量的误解
- python - 从 Python 中的字母数字字符串列表执行数字降序然后升序排序
- cmake - 为什么 xerces 将 XMLCh 更改为 char16_t,我可以将其更改回 wchar_t 吗?
- excel - 将特定列提取到多个 .CSV 中,代码错误
- firebase - 如何从 Firestore 中检索这些数据?
- powerbi - 如何避免 pbix 选择“第一个”值?
- powershell - 在开始作业脚本块中使用 \\?\UNC\ (长 unc 路径)时,get-itemPropertyValue 不绑定路径
- wordpress - 禁用 Wocommerce 订阅续订订单
- python - 如何在 Django 1.11 中创建迁移删除表?