ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • [JavaScript jQuery] 7장 생성자 함수
    GOhACK/웹 2016. 12. 28. 12:52

    7.2 프로토타입


    예제 오류> 무엇을 잘못했지?

    <script>
        function Student() {
            this.이름 = name;
            this.국어 = korean;
            this.수학 = math;
            this.영어 = english;
            this.과학 = science;
        }
    
        Student.prototype.getSum = function() {
            return this.국어 + this.수학 + this.영어 + this.과학;
        };
        Student.prototype.getAverage = function() {
            return this.getSum() /4;
        }
        Student.prototype.toString = function() {
            return this.이름 +'\t' + this.getSum() + '\t' + this.getAverage();
        };
    
        // create student arrays
        var students = [];
        students.push(new Student('윤하린', 96, 98, 92, 98));
        students.push(new Student('윤인아', 96, 96, 85, 76));
    
        // display
        var output = '이름\t총첨\t평균\n';
        for(var i in students) {
            output += students[i].toString() + '\n';
        }
    
        alert(output);
    
    </script>


    7.3 new 키워드


     - 생성자 함수를 생성할 때 new 키워드를 사용하는 경우

    <script>
        // create constructor function
        function Constructor (value) {
            this.value = value;
        }
    
        // declare a variable
        var constructor = new Constructor('Hello');
    
        // display
        alert(constructor.value);
    </script>



    - new 키워드를 사용하지 않을 때

    <script>
        // create constructor function
        function Constructor (value) {
            this.value = value;
        }
    
        // declare a variable
        var constructor = Constructor('Hello');
    
        // display
        alert(value);
    </script>


    출력은 모드 'Hello' 의 경고창으로 나온다.


    this 키워드: window 객체를 가리킴

    new 키워드: 객체를 위한 공간을 만들고 this 키워드가 해당 공간을 의미.


    7.4 캡슐화

    캡슐화: 잘못 사용될 수 있는 객체의 특정 부분을 사용자가 사용할 수 없게끔 막는 기술



    7.5 상속

    코드 7-17 응용


    Square.prototype.constructor = Square; 

    이 코드를 적음으로써 Square의 생성자 함수가 Square을 가리키도록 합니다.

     코드 7-17 응용한 부분은 출력해보면 생성자 함수 Rectangle을 가리킵니다.

     (참고 블로그:http://superjang.com/archives/2535)













    'GOhACK > ' 카테고리의 다른 글

    [JavaScript JQuery] 6장 객체  (0) 2016.12.28
    [JavaScript JQuery] 5장 함수  (0) 2016.12.24
    [JavaScript JQuery] 4장 반복문  (0) 2016.12.24
    [JavaScript JQuery] 3장 조건문  (0) 2016.12.24

    댓글

Designed by Tistory.