什么是 JavaScript 中的“影子标识符声明”?

What is "Shadow Identifier Declaration" in JavaScript?

提问人:Aaditya Sharma 提问时间:2/11/2017 最后编辑:isherwoodAaditya Sharma 更新时间:10/21/2022 访问量:1866

问:

在阅读一篇 JavaScript 文章时,我遇到了这个术语“影子标识符声明”。有人可以解释这是什么吗?如果可能的话,请提供一个简单的例子。

snapshot from the article

JavaScript的

评论

1赞 Bergi 2/11/2017
有影子,但“影子标识符声明”不是一个固定的术语。

答:

10赞 T.J. Crowder 2/11/2017 #1

当您在作用域中声明一个标识符时,该标识符隐藏了包含在包含作用域中存在的标识符:

var foo; // The outer one
function example() {
    var foo; // The inner one -- this "shadows" the outer one, making the
             // outer one inaccessible within this function
    // ...
}

有几种方法可以隐藏某些内容:

  1. 使用变量声明 (, , ),如上所述varletconst

  2. 使用参数声明:

    var foo; // The outer one
    function example(foo) { // This parameter shadows the outer `foo`
        // ...
    }
    
  3. 使用函数声明:

    var foo; // The outer one
    function example() {
        function foo() { // This shadows the outer `foo`
        }
        // ...
    }
    

...和其他几个。在作用域中声明标识符并在包含作用域中隐藏(隐藏)标识符的任何内容,即隐藏声明/定义。

评论

1赞 lonesomeday 2/11/2017
命名函数语句和 catch 块也可以屏蔽外部变量。
3赞 KAD 2/11/2017 #2

维基百科定义(https://en.wikipedia.org/wiki/Variable_shadowing):

在计算机编程中,当变量 在一定范围内声明(决策块、方法或内部 class) 与在外部作用域中声明的变量同名。在 标识符(名称,而不是变量)的级别,这是已知的 作为名称掩码。据说这个外部变量被 内部变量,而内部标识符被说成是屏蔽外部变量 标识符。这可能会导致混淆,因为可能不清楚哪个 变量后续使用阴影变量名称所指的,其中 取决于语言的名称解析规则。

Java 示例:

public class Shadow {
        private int myIntVar = 0;

        public void shadowTheVar(){

            // since it has the same name as above object instance field, it shadows above 
            // field inside this method
            int myIntVar = 5;

            // If we simply refer to 'myIntVar' the one of this method is found 
            // (shadowing a seond one with the same name)
            System.out.println(myIntVar);

            // If we want to refer to the shadowed myIntVar from this class we need to 
            // refer to it like this:
            System.out.println(this.myIntVar);
        }

        public static void main(String[] args){
            new Shadow().shadowTheVar();
        }
    }
0赞 user7486067 4/24/2017 #3

对于您的问题,请考虑以下代码

function foo(a) {
var b = 2;
// some code
function bar() {
// ...
}
// more code
var c = 3;
}

在此代码片段中,当您尝试从全局范围执行时。

bar(); // fails
console.log( a, b, c ); // all 3 fail

假设在函数 bar(){ .... } 中,如果您有其他代码,例如

function foo(){
var b = 3;
console.log(b);
}

那么这意味着 foo lin the bar 在全局范围内隐藏了 foo(a)

-1赞 Ignacio Jimenez 10/21/2022 #4

此错误:当您以大写字母调用服务类时,也会出现此错误。TSLint: Shadowed name: 'AccountService'(no-shadowed-variable

Angular 框架、typeScript

所以,如果我用小写字母设置它:与小写字母相同

评论

0赞 VLAZ 10/26/2023
这里关于 TS 或类没什么特别的。constructor 参数与外部标识符同名,它隐藏了它。这已经可以通过阴影的工作原理来解释 - 如果参数与外部标识符同名,则参数会隐藏它。