在函数中使用与函数同名的变量是否正常? [英] Is it normal to use in the function some variable with the same name as it function?

查看:50
本文介绍了在函数中使用与函数同名的变量是否正常?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在函数中使用与函数同名的变量是否正常?

Is it normal to use in the function some variable with the same name as it function?

const sum = function(arr) {
  let sum = 0;
  for(let i = 0; i < arr.length; i++)
    sum += arr[i]; 
  return sum;
};

这段代码运行良好,没有任何警告.但我很好奇它会导致任何麻烦吗?

This code works fine without any warnings. But I'm curious can it lead to any trouble?

推荐答案

隐藏"变量名称通常是不好的做法.如果您不小心,可能会导致对所引用内容的混淆.

It's generally bad practice to "shadow" variable names. It can cause confusion about what's being referenced if you aren't careful.

在此示例中,没有主要缺点.考虑一下,如果以后你决定使函数递归.如果你试图从它自身内部调用 sum,你会得到一个错误,指出 sum 不是一个函数,因为它正在寻找内部变量 sum,而不是函数.这不是主要问题,但编写将来不太可能以奇怪方式破坏的代码是个好主意.你永远不知道你以后可能会做出什么改变.

In this example, there isn't a major downside. Consider though if later you decided to make the function recursive. If you tried to call sum from within itself, you'd get an error that sum isn't a function, because it's finding the inner variable sum, not the function. That's not a major issue, but it's a good idea to write code that is less likely to break in weird ways in the future. You never know what changes you might make later on.

这篇关于在函数中使用与函数同名的变量是否正常?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆