An example of variable shadowing in javascript

2019-01-02 21:12发布

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");​

3条回答
无与为乐者.
2楼-- · 2019-01-02 21:29

That is also what is known as variable scope.

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

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.

查看更多
伤终究还是伤i
3楼-- · 2019-01-02 21:47

In computer programming, variable shadowing occurs when a variable declared within a certain scope (decision block, method, or inner class) has the same name as a variable declared in an outer scope. This outer variable is said to be shadowed...

so I believe your example is good.

you have a globally named variable that shares the same name as inner method. the inner variable will be used only in that function. Other functions without that variable declaration will use the global one.

查看更多
初与友歌
4楼-- · 2019-01-02 21:50

Yes, your example is an example of shadowing.

The shadowing will persist in other scenarios too due to how closures work in JavaScript. Here's an example:

var x = -1;
function xCounter() {
    var x = 0;
    return function() {
        ++x;
        return x;
    };
}

console.log(x);   // -1
counter = xCounter();
console.log(counter());   // 1
console.log(counter());   // 2
console.log(x);   // still -1, global was never touched

Note that in this case, even when xCounter returns, the function it returns still has a reference to its own x and invocations of that inner function have no effect on the global, even though the original has long since gone out of scope.

查看更多
登录 后发表回答