[英]JavaScript Custom Function defined as a Variable, Should the Declaration be a 'var' or 'let' or 'const'?
I have code-smell suggestion to add declaration to below function.我有 code-smell 建议在 function 以下添加声明。
Add the "let", "const" or "var" keyword to this declaration of "nullToEmpty" to make it explicit.将“let”、“const”或“var”关键字添加到“nullToEmpty”的声明中,使其显式化。
nullToEmpty = function (obj) {
if(typeof obj == 'undefined'){
return null;
}else{
return JSON.parse( JSON.stringify(obj).replace(/:null/gi, ':""') );
}
};
I wonder what is the most appropriate declaration type for this type of a function, should I use const ?我想知道这种类型的 function 最合适的声明类型是什么,我应该使用const吗?
const nullToEmpty = function (obj) {
if(typeof obj == 'undefined'){
return null;
}else{
return JSON.parse( JSON.stringify(obj).replace(/:null/gi, ':""') );
}
};
var
is the "old way" of declaring variables - it can be redeclared, and its scope is local ( only exists inside the current function ) if declared inside a function, and global otherwise. var
是声明变量的“旧方法”——它可以重新声明,如果在 function 中声明,则它的 scope 是本地的(仅存在于当前的 function 中),否则是全局的。 It might be useful in some cases, but it's not that recommended anymore since the global scope may cause some undesired effects if not used with caution.它在某些情况下可能有用,但不再推荐,因为如果不谨慎使用全局 scope 可能会导致一些不良影响。
let
is a newer declaration, and has almost the same behaviour as var
, but the scope is always local. let
是一个较新的声明,其行为与var
几乎相同,但 scope 始终是本地的。
const
is also always local, but it differs because it cannot be redeclared. const
也始终是本地的,但不同之处在于它不能重新声明。 That is a little bit misleading sometimes, though, because "you can't redaclare" does not mean "you can't alter it".不过,这有时有点误导,因为“你不能重新声明”并不意味着“你不能改变它”。
That works as expected for primitive values ( strings, numbers, etc ), but not for objects, arrays or functions.这对于原始值(字符串、数字等)按预期工作,但不适用于对象、arrays 或函数。
This is invalid code:这是无效的代码:
const primitive = 1;
primitive = 2;
This is valid:这是有效的:
const array = [1, 2, 3];
array.push(4);
So, with all that said: yes, I would use const
in that scenario.所以,综上所述:是的,我会在那种情况下使用
const
。 Your function declaration is not going to change, and there is no need for it to be of a global scope.您的 function 声明不会更改,也不需要是全局 scope。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.