【问题标题】:I declared a variable with const after a function, why is it still accessible there?我在函数之后用 const 声明了一个变量,为什么它仍然可以在那里访问?
【发布时间】:2020-07-28 06:44:25
【问题描述】:

这段代码正在运行,对我来说这是一种奇怪的行为,因为不应该提升 'const' 变量。有人能解释一下它的工作原理和原因吗?

describe("should dummy tests", () => {

let fixture: ComponentFixture<DummyComponent>;
let component: DummyComponent;
let element: HTMLElement;

beforeEach(async () => {
    await TestBed.configureTestingModule({
        declarations: declarations
    }).compileComponents();


    fixture = TestBed.createComponent(DummyComponent);
    component = fixture.componentInstance;
    element = fixture.nativeElement as HTMLElement;

    fixture.detectChanges();
});

it("should dummy text", async () => {
    expect(element.querySelector("dummy-selector")).toBeTruthy();
});
});

const declarations = [DummyComponent];

【问题讨论】:

    标签: javascript angular testing ecmascript-6 jestjs


    【解决方案1】:

    因为实际的函数调用发生在指定“声明”变量之后。检查这两个例子:

    function logNumber() {
      console.log(number)
    }
    
    logNumber()
    
    const number = 22
    // output: Cannot access 'number' before initialization
    

    同时:

    function logNumber() {
      console.log(number)
    }
    
    const number = 22
    
    logNumber()
    // output: 22
    

    在第二个示例中,全局执行上下文由 logNumber 函数调用访问。顺便说一句,'const' 和 'let' 变量也被提升了,但它们没有被初始化为 'undefined',它们保持未初始化状态。

    更多信息: Javascript Execution Contexts

    【讨论】:

    • 实际的函数调用之后是如何工作的?你知道业力运行是如何运作的吗?
    【解决方案2】:

    该常量只需要在访问它的代码求值之前声明(即在调用相关函数时)。

    代码的编写顺序无关紧要。

    function example () {
        console.log(`The value of foo is ${foo}`);
    }
    
    try {
        example();
    } catch (e) {
        console.log("There was an error in the first attempt!");
    }
    const foo = 1;
    try {
        example();
    } catch (e) {
        console.log("There was an error in the second attempt!");
    }

    【讨论】:

      猜你喜欢
      • 2020-07-20
      • 2013-02-09
      • 2020-09-29
      • 1970-01-01
      • 2012-04-29
      • 1970-01-01
      • 2017-07-20
      • 2021-07-24
      • 1970-01-01
      相关资源
      最近更新 更多