티스토리 뷰

728x90
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>
    <!-- 
            * 생성자 함수 
                    : 객체를 생성할 때 사용하는 함수

                    -   실제 ECMAScript 2015 이전에 다른 언어에서 사용한 객체 지향과 비슷한 형식으로, 객체를 생성하고자 고안한 로직
                    -   기존 함수에 new 연산자를 붙여 호출하면, 그 함수는 생성자 함수로 둔갑하게 됨
                    -   JS에서는 특정 함수가 생성자 함수로 정의되어 있음을 알리기 위해 함수 이름의 첫 문자를 암묵적으로 대문자로 쓰길 권장함
                    -   생성자 함수 호출 시, 생성자 함수 내부에 존재하는 this는  함수로 생선한 자기 자신을 가리킴 (일반 함수호출 방식에서의 this와는 다르게)
                    -   생성자 함수로 인스턴스 생성되면, 그 인스턴스는 기존 함수에서 Prototype으로 참조하던 객체를 그대로 __proto__로 참조함
                    -   객체 리터럴 방식과 생성자 함수 방식은 프로토타입에서 차이가 갈림
                    -   객체 리터럴 방식 : Object를 프로토 타입 객체를 자신의 프로토 타입 객체로 설정 
                    -   생성자 함수 방식 : 생성자 함수의 Prototype 프로퍼티가 가리키는 객체를 자신의 프로토타입 객체로 설정
                    -   생성자 함수를 new로 선언하지 않고 호출 시, 일반 함수 호출처럼 로직 수행됨
                    -   내부의 this는 window를 가리키므로 전역 객체에 모든 프로퍼티가 바인딩 된다.
     -->

    <script>
        /* const a1 = {
            a : 12345
        } */


        function Person() {
            this.name = 'Soheny';
        }

        const p1 = new Person();
        console.dir(p1); //Person : 생성자 함수로 선언된 객체


        const p2 = {
            name : 'Soheny'
        }
        console.dir(p2); //Obejct : 일반적인 객체
    </script>
</body>

</html>

 

 

 

 

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>
    <script>
        function Car() {
            this.type = "전기차";
            this.excel = function() {
                console.log("달립니다.");
            }
            this.break = function() {
                console.log("멈춥니다.");
            }
        }

        Car.prototype.charge = function() {
            console.log("충전 중입니다.");
        }

        const car1 = new Car();
        console.dir(car1);

        car1.charge(); //충전 중입니다. : Car함수의 prototype이고,  car1은 Car의 생성자 함수로 만들어진 함수이므로 charge 사용할 수 있다. 
    </script>
</body>

</html>

 

 

 

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>
    <!-- 
            * 함수 리턴
                        : JS함수는 항상 리턴 값을 반환하는 구조로 이뤄짐
                        

                        -   RETURN값  쓰지 않아도 엔진에서 JS 랜더링하는 과정 중 RETURN을 암묵적으로 아래에 추가해 메모리 반환이 이뤄지도록 함
                        -   RETURN문 사용하지 않아도 다음 규칙으로 항상 리턴값 전달
                                1. 일반 함수나 메서드는 리턴값을 지정하지 않을 때 ''UNDEFINED' 값 리턴
                                2. 생성자 함수에서 리턴 값 지정 하지 않을 때, 생성된 객체가 리턴
                                3. 생성자 함수에서 리턴값으로 넘긴 값이 객체가 아닌 Boolean, Number, String의 경우, 리턴값 무시하고 this로 바인딩된 객체가 리턴됨
     -->

     
    <script>
        // new를 사용하지 않고, 생성자 함수 사용하는 방법
        function Person(name, age, gender) {
            // this는 Window를 가리킴
            // this가 Person객체에 해당하는 것이 아니라면 return new Person 실행, 그렇지 않으면 아래 실행
            if(!(this instanceof Person)){
                return new Person(name, age, gender);
            }
            this.name = name;
            this.age = age;
            this.gender = gender;
        }

        const obj = Person("Soheny", 31, "Unknown");
        console.log(obj); // Person{name : 'Soheny', age : 31, gender : ''Unknown}

        // 생성자 함수를 사용하지 않으면 그냥 각각 나와버림
        // 생성 후에는 Undefined로 나옴
        console.log(window.name); //Soheny
        console.log(window.age); //31
        console.log(window.gender); //Unknown
    </script>
</body>

</html>

 

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>
        <script>
        function Person(name, age, gender) {
            this.name = name;
            this.age = age;
            this.gender = gender;

            return 5;
        }

        // new를 사용한 생성자 함수 생성법
        const obj = new Person("Soheny", 31, "Unknown");
        console.dir(obj); // Person
        </script>
</body>

</html>

 

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>

    <!--     
            *  생성자 함수 메서드 선언

                    : 생성자 함수 내에서 메서드를 선언할 경우, 객체 생성시 많이 메모리 소모됨
                    - 생성자 함수를 통해 가독성, 재사용성 개선 될 수 있어도, 웹이 무거워지는 단점 있음
                    - 생성자 함수의 특징 활용해 속성은 기존처럼 생성자 함수 내에 선언하고,
                      메서드는 생성자 함수의 prototype통해 선언하도록 권장됨
                    - 객체를 여러개 생성자 함수로 선언해도 메모리 적게 차지함
     -->

     
    <script>

        const Car = function(type, company, name) {
            this.type = type;
            this.company = company;
            this.name = name;
            // 내부에 선언하게 되면 계속 상단의 변수를 생성해서 공간 낭비 초래 > 하지만 기능을 따로 실행시키지 않아도 되는 장점이 있음
/*             this.excel = function() {
                console.log("출발합니다");
            }
            this.break = function() {
                console.log("멈춥니다");
            } */
        }

        // 새로운 기능은 아래에 프로토타입 추가로 선언해줘야 위의 function을 한 번만 선언하여 공간 낭비를 줄임 > 메모리 절약, but 기능을 매번 실행시키므로 번거로움 > 메모리 절약 이점이 더 크기 때문에 사용
        Car.prototype.excel = function() {
            console.log("출발합니다");
        }
        Car.prototype.break = function() {
            console.log("멈춥니다");
        }

        const obj = new Car("전기", "테슬라", "모델X");
        console.dir(obj);
        obj.excel();
    </script>
</body>

</html>

 

 

 

728x90
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2025/07   »
1 2 3 4 5
6 7 8 9 10 11 12
13 14 15 16 17 18 19
20 21 22 23 24 25 26
27 28 29 30 31
글 보관함