퀴즈 하나 내본다. 맞춰봐라. 상품은 없다.
두개의 파일이 있다고 해보자
hello.ts
class Greeting {
say() {
const a = Math.random() * 0.3;
return `hello ${a}`;
}
}
export const hello = new Greeting();
index.ts
import { hello } from "./hello";
const d = hello;
const e = hello;
console.log(d === e);
index.ts에서 console에 찍히는 값은 무엇일까?
답은 true이다. 왜 true인지 파해쳐 보려 한다.
code 실행 시 import statement가 hoisted 된다. 이 말은 코드가 돌기 전에 먼저 다뤄진다는 말이다.
처음 import가 될 때 import 된 코드가 실행된다.
여러번 import 된다면, 그 코드는 딱 한번 실행된다. (처음 실행된 코드 그대로)
그래서 d와 e의 instance reference가 같아서 true가 노출된다.
Read-Only Live Bindings
import 된 값은 수정할 수 없다. 즉 change, overwrite(re-assign) 할 수 없다.
import { someValue } from './module.js';
someValue = 10; // This will cause an error because it's read-only
import 된 값은 항상 최신 값으로 준다.
// file1.js
export let counter = 0;
setInterval(() => {
counter++; // counter value changes over time
}, 1000);
// file2.js
import { counter } from './file1.js';
console.log(counter); // This will log the latest value of counter every time you access it
'IT > javascript' 카테고리의 다른 글
[JS] var 에 대해서 그리고 hoisting 까지 (0) | 2024.09.12 |
---|---|
[JS] 제너레이터 함수 (generator function) (0) | 2024.07.07 |
[JS] prototype (0) | 2024.04.30 |
[JS] if else 리팩토링 (중첩 조건문 처리하기) > 코드 변환 스냅샷 (0) | 2024.04.29 |
[JS] if else 리펙토링 (객체 + 함수) (0) | 2024.04.29 |