简体   繁体   English

有没有办法在 Function 中禁用全局变量声明

[英]Is there a way to disable Global Variable Declaration within Function

I ran into a issue eventually it turned out because I did not use var prefix during declare a local variable within a function, so when it get to next function it actually automatically pick it up the variable, even though that was a syntax mistake as my initial intent is to use another local variable with similar name.我最终遇到了一个问题,结果是因为我在 function 中声明局部变量时没有使用var前缀,所以当它到达下一个 function 时,它实际上会自动选择变量,即使这是我的语法错误最初的意图是使用另一个具有相似名称的局部变量。 So is there a setting on google apps script to throw error on a global variable declaration within function to avoid this kind of tricky issues?那么在 function 内的 global variable declaration 上是否有 google apps script 设置抛出错误来避免这种棘手的问题?

Here is sample code of my problematic issue这是我的问题的示例代码

function f1(){
   for(var idx=0;idx<length; idx++){
     tmp1 = idx;  // since tmp1 missing var, it endup as global variable
     ...
   }
}
function f2(){
   Logger.log(tmp1);// even though I did not delcare tmp1 here, it will not throw either validation nor runtime error.
}

Use the JavaScript strict mode.使用 JavaScript 严格模式。 To do this, add the following at the global scope:为此,在全局 scope 添加以下内容:

'use strict';

The above string literal could be added on any file in your Google Apps Script project, just be sure to add it outside of any function. In order to make this easier to find, add it on top of your project's first file.上面的字符串文字可以添加到您的 Google Apps 脚本项目中的任何文件中,只需确保将它添加到任何 function 之外。为了更容易找到它,请将它添加到您项目的第一个文件之上。

Resources资源

Related有关的

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM