javascript中变量阴影的一个例子 [英] An example of variable shadowing in javascript

查看:117
本文介绍了javascript中变量阴影的一个例子的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 Eloquent Javascript(第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.

这是阴影的一个例子吗?

Is this an example of shadowing?

var currencySymbol = "$";

function showMoney(amount) {
  var currencySymbol = "€";
  document.write(currencySymbol + amount);
}

showMoney("100");​


推荐答案

这也就是所谓的变量范围

变量仅存在于其包含的函数中/ method / class,那些将覆盖属于更广范围的任何变量。

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天全站免登陆