此代码有效,对我来说,这是一种奇怪的行为,因为对于'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];
因为实际的函数调用在指定'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'初始化,而是保持未初始化状态。
只需在访问该代码的代码之前先声明该常量求值(即,在调用相关函数时)。
编写代码的顺序无关紧要。
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!");
}