묻고 답해요
156만명의 커뮤니티!! 함께 토론해봐요.
인프런 TOP Writers
-
미해결
블록레벨 스코프, 스코프 체인과 관련해 궁금한 점이 있습니다.
if (true) { let y = 'hi'; function test() { console.log(y); } } console.log(y); // ReferenceError: y is not defined test(); // hi위 코드 실행 시 console.log(y)는 참조 에러, test()는 'hi'가 출력되어집니다.제가 알기론 자바스크립트는 코드 블럭이 아닌 함수에 의해서 지역 스코프가 생긴다(함수 레벨 스코프)고 알고 있습니다. 따라서 if문(블록문) 내에 정의한 test 함수를 전역에서 호출해도 에러가 발생하지 않는 것이고요.let, const 키워드로 선언한 변수의 경우 블록 레벨 스코프를 가지기 때문에 전역에서 y 변수 참조 시 참조 에러가 발생하는 것도 이해할 수 있습니다.제가 궁금한 것은test 스코프의 상위 스코프는 전역 스코프가 아닌지?test 스코프의 상위 스코프가 if문 블록 스코프라면 전역에서 test함수 호출 시 참조에러가 발생해야하는거 아닌가요?(엄격 모드일 경우 참조에러 발생, 비엄격 모드일 땐 위 처럼 'hi'출력)그렇다면 test 함수 내에서는 y를 참조할 경우 test 함수 내부에 y가 있는지 찾은 후 없기 때문에 스코프 체인에 따라 전역에 y가 있는지 찾고 이 경우에도 없기 때문에 참조에러가 발생해야하는 것이 아닌지? 어떻게 블록 레벨의 'hi'를 찾을 수 있는지?입니다.잘못된 개념이 있다면 알려주시면 감사하겠습니다 ㅜㅜ
-
해결됨스프링 프레임워크 핵심 기술
"Prototype/프록시"로 설정했는데 동일한 객체로 나옵니다
@Getter @Component @Scope(scopeName = ConfigurableBeanFactory.SCOPE_PROTOTYPE, proxyMode = ScopedProxyMode.TARGET_CLASS) public class Prototype { private final UUID uuid = UUID.randomUUID(); } @Getter @Component @RequiredArgsConstructor public class Singleton { private final Prototype prototype; public void print() { System.out.println(prototype.getUuid()); System.out.println(prototype.getUuid()); System.out.println(prototype.getUuid()); } } Singleton singleton = context.getBean(Singleton.class); singleton.print(); Prototype p1 = singleton.getPrototype(); Prototype p2 = singleton.getPrototype(); System.out.println(p1); System.out.println(p2); System.out.println(p1.getUuid()); System.out.println(p2.getUuid()); System.out.println(p1 == p2); System.out.println(p1.equals(p2)); System.out.println(new Prototype().equals(new Prototype())); Singleton bean 안에 class를 target으로 하는 proxy로 prototype의 bean을 필드로 정의했습니다. 근데 singleton 객체에서 prototype 필드를 print하면 메모리 주소는 다르게 나오는데 ==, equals 등으로 비교하면 true가 나오는 기이한 현상을 겪고 있습니다. 제 자바 근간이 흔들리고 있어요; 왜 그런 걸까요..?