我在函数后用const声明了一个变量,为什么在那里仍然可以访问它?

问题描述 投票:0回答:2

此代码有效,对我来说,这是一种奇怪的行为,因为对于'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
2个回答
2
投票

因为实际的函数调用在指定'declarations'变量之后发生。检查以下两个示例:

function logNumber() {
  console.log(number)
}

logNumber()

const number = 22
// output: Cannot access 'number' before initialization

while:

function logNumber() {
  console.log(number)
}

const number = 22

logNumber()
// output: 22

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

更多信息:Javascript Execution Contexts


0
投票

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

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

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!");
}
© www.soinside.com 2019 - 2024. All rights reserved.