这是JavaScript中可变阴影的示例吗? [英] Is this an example of variable shadowing in JavaScript?

查看:53
本文介绍了这是JavaScript中可变阴影的示例吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在高级Java语言(第3章)中了解了变量阴影这一术语,但是我正在尝试了解该概念的精确的基本示例.

I learnt about the term variable shadowing in Eloquent Javascript (Chapter 3), but I am trying to understand a precise, basic example of the concept.

这是阴影的例子吗?

var currencySymbol = "$";

function showMoney(amount) {
  var currencySymbol = "€";
  console.log(currencySymbol + amount);
}

showMoney("100");

推荐答案

这也称为变量范围.

变量仅存在于其包含的函数/方法/类中,并且这些变量将覆盖属于更大范围的任何变量.

A variable only exists within its containing function/method/class, and those will override any variables which belong to a wider scope.

这就是在您的示例中将显示欧元符号而不是美元的原因. (因为包含美元的currencySymbol的范围比包含欧元符号的currencySymbol的(全球)范围大.)

That's why in your example, a euro sign will be shown, and not a dollar. (Because the currencySymbol containing the dollar is at a wider (global) scope than the currencySymbol containing the euro sign).

关于您的特定问题:是的,这是可变阴影的一个很好的例子.

As for your specific question: Yes, that is a good example of variable shadowing.

这篇关于这是JavaScript中可变阴影的示例吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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