투케이2K

564. (javaScript) 자바스크립트 new Function 사용해 동적 string 문자열 소스 코드 작성 후 함수 실행 - 파라미터 첨부 본문

JavaScript

564. (javaScript) 자바스크립트 new Function 사용해 동적 string 문자열 소스 코드 작성 후 함수 실행 - 파라미터 첨부

투케이2K 2026. 6. 29. 20:21
728x90
반응형

[개발 환경 설정]

개발 툴 : Edit++ / Vscode

개발 언어 : JavaScript

 

[소스 코드]

-----------------------------------------------------------------------------------------
[사전 설명 및 설정 사항]
-----------------------------------------------------------------------------------------

- 개발 환경 : Web


- 개발 기술 : JavaScript / Function / String


- 사전) 👉 자바스크립트 new Function() 간략 설명 : 

  >> new Function() 은 문자열로 작성된 코드를 런타임에 함수로 생성하는 JavaScript 기능입니다.

    - 쉽게 말하면 eval() 과 비슷하게 문자열을 실행할 수 있지만, 실행 결과가 함수 객체라는 점이 다릅니다.

  >> new Function() 정리 :

    - 문자열을 함수로 컴파일합니다.

    - eval()과 유사하지만 함수 객체를 반환합니다.

    - 현재 스코프를 캡처하지 않고 전역 스코프에서 실행됩니다.

-----------------------------------------------------------------------------------------





-----------------------------------------------------------------------------------------
[소스 코드]
-----------------------------------------------------------------------------------------

<!DOCTYPE HTML>
<html lang="ko" translate="no">
<head>
    <title>javaScriptTest</title>

    <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">

    <!-- 반응형 구조 만들기 -->
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0, user-scalable=no">

    <!-- Chrome / Edge (Chromium)에서 자동 번역 기능을 완전히 비활성화 -->
    <meta name="google" content="notranslate">

    <!-- 내부 CSS 스타일 지정 -->
    <style>

      html, body {
        width: 100%;
        height: 100%;
        margin : 0 auto;
        padding : 0;
        border : none;
        background-color: #666;
      }

    </style>





    <!-- [CDN 주소 설정] --> 
    <script src="https://code.jquery.com/jquery-latest.min.js"></script>






    <!-- [자바스크립트 코드 지정] -->
    <script type="module">    


      // -----------------------------------------------------------------
      // ✅ [Window.onload 웹 브라우저 로드 완료]
      // -----------------------------------------------------------------
      window.onload = async function() {
        console.log("[window onload] : [html 최초 로드 및 이벤트 상시 대기 실시] : [start]");

        try {

          // ------------------------------------------------
          // 🟦 동적 함수 실행할 코드 정의 : 파라미터 인자 없음
          // ------------------------------------------------ 
          const code_1 = `

            const array = ["hello", "towk", "2k"];
            
            const idx = Math.floor(Math.random() * (array.length - 1) ) + 0; // 0 ~ array 범위 랜덤

            // ---------------------------
            // [리턴 반환 코드]
            // ---------------------------            
            return array[idx]; // 동적 array 데이터 반환
            
            //return Math.floor(Math.random() * 10) + 1; // 1 부터 10 범위 랜덤 정수 값 반환
          `;

          const fn_1 = new Function(code_1); // Function 생성
          console.log("fn_1 run : ", fn_1()); // 코드 실행 및 호출



          // ------------------------------------------------
          // 🟦 동적 함수 실행할 코드 정의 : 파라미터 인자 포함
          // ------------------------------------------------ 
          const code_2 = `

            const addValue = a + b; // 파라미터 값 더하기 수행

            // ---------------------------
            // [리턴 반환 코드]
            // ---------------------------            
            return addValue;
          `;

          const fn_2 = new Function('a', 'b', code_2); // Function 생성
          console.log("fn_2 run : ", fn_2(10, 20)); // 코드 실행 및 호출
          
        }
        catch (exception) {
          console.error("[window onload] : [Exception] : ❌ 예외 상황 발생 : ", exception);

        }

      };


    </script>


</head>


<body>

</body>

</html>

-----------------------------------------------------------------------------------------





-----------------------------------------------------------------------------------------
[참고 사이트]
-----------------------------------------------------------------------------------------

▶️ 562. (javaScript) 자바스크립트 new Function 사용해 문자열로 작성 된 소스 코드 동적 런타임 함수 생성 및 실행 수행

https://kkh0977.tistory.com/8940

https://blog.naver.com/kkh0977/224328272045


▶️ 520. (javaScript) [간단 소스] 자바스크립트 동적 스크립트 작성 및 window.open 시 window.opener.postMessage 부모에서 자식 데이터 전송

https://kkh0977.tistory.com/8733

https://blog.naver.com/kkh0977/224237361564?trackingCode=blog_bloghome_searchlist


▶️ 514. (javaScript) [간단 소스] 자바스크립트 string 문자열 형식 동적 자바 스크립트 코드 작성 및 import 모듈 로딩 , 소스 코드 실행

https://kkh0977.tistory.com/8708

https://blog.naver.com/kkh0977/224222595694?trackingCode=blog_bloghome_searchlist


▶️ 499. (javaScript) 자바스크립트 동적 html 코드 작성 및 Script 스크립트 코드 작성 후 window open 동작 테스트

https://kkh0977.tistory.com/8660

https://blog.naver.com/kkh0977/224200029328?trackingCode=blog_bloghome_searchlist


▶️ 87. (javascript/자바스크립트) 동적으로 form 폼 생성해 get, post 데이터 전송 실시

https://kkh0977.tistory.com/938

https://blog.naver.com/kkh0977/222420762770?trackingCode=blog_bloghome_searchlist


▶️ 561. (javaScript) 자바스크립트 setInterval 사용해 주기적 JSON 특정 Key 의 Value 값 동적 업데이트 수행

https://kkh0977.tistory.com/8939

https://blog.naver.com/kkh0977/224327264210?trackingCode=blog_bloghome_searchlist

-----------------------------------------------------------------------------------------
 
728x90
반응형
Comments