본문 바로가기
IT/javascript

[javascript] import 자세하게 파해쳐보자

by 내일은교양왕 2024. 9. 12.

퀴즈 하나 내본다. 맞춰봐라. 상품은 없다.

 

두개의 파일이 있다고 해보자

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