Computer >> 컴퓨터 >  >> 프로그래밍 >> JavaScript

JavaScript 'with' 키워드 사용법 – 객체 속성 참조를 간결하게 만드는 방법

JavaScript의 with 키워드는 객체의 속성(property)이나 메서드(method)에 반복적으로 접근할 때 사용하는 일종의 축약 표현입니다.

with 블록 안에서는 인자로 지정한 객체가 해당 블록 동안 기본 객체(default object)로 설정됩니다. 따라서 객체 이름과 점(.) 연산자 없이도 그 객체의 속성과 메서드를 바로 사용할 수 있습니다.

문법(Syntax)

with 키워드의 기본 문법은 다음과 같습니다.

with (object){
    // 객체 이름과 점(.) 없이 속성과 메서드 사용
}

예제(Example)

다음 코드는 사용자 정의 객체에서 with 키워드를 활용해 책의 가격(price)을 설정하는 예제입니다.

<html>
   <head>
      <title>User-defined objects</title>
      <script>
         // 메서드 역할을 수행할 함수 정의
         function addPrice(amount){
            with(this){
               price = amount;
            }
         }
         function book(title, author){
            this.title = title;
            this.author = author;
            this.price = 0;
            this.addPrice = addPrice; // 메서드를 속성으로 할당
         }
      </script>
   </head>
   <body>
      <script type="text/javascript">
         var myBook = new book("Python", "Tutorialspoint");
         myBook.addPrice(100);

         document.write("Book title is : " + myBook.title + "<br>");
         document.write("Book author is : " + myBook.author + "<br>");
         document.write("Book price is : " + myBook.price + "<br>");
      </script>
   </body>
</html>

실행 결과(Output)

Book title is : Python
Book author is : Tutorialspoint
Book price is : 100

주의 사항

with 키워드는 코드를 짧게 줄여 주지만, 값이 어느 객체의 속성인지 명확하지 않아 가독성과 디버깅에 불리하고 성능 저하를 유발할 수 있습니다. 이러한 이유로 ECMAScript 5부터 strict 모드('use strict')에서는 with의 사용이 금지되어 있으며, 최신 JavaScript 개발 환경에서는 권장되지 않습니다. 실무에서는 구조 분해 할당(destructuring)을 사용하거나 객체를 별도의 변수에 담아 참조하는 방식이 훨씬 안전하고 명확한 대안입니다.