본문 바로가기

자바스크립트

속성과 메서드 21. 02. 26.

메서드

- this 키워드

    <script>
        var obj = {
            name : "자바맨",
            print : function() {
                alert(this.name + "님 안녕"); // this 안 쓰면 name이 안 나옴
            }
        };
        // this : "가장 가까운" 객체의 주소값
        // obj.print();

        obj.age = 30;
        delete obj.age; // 잘 쓰진 않음.
        for(var i in obj) {
            document.write(i + "::" + obj[i], "<br>")
        }
        document.write("name" in obj, "<br>");
        document.write("age" in obj, "<br>");
    </script>

 

    <script>
        // 자바스크립트를 객체처럼 써 보는 예제
        var names = ["윤인성", "연하진", "구지연", "나선주", "윤영월", "김미화", "김연화", "박아현", "서준서", ]

        var student = {}; // 객체
        var students = new Array(names.length); // 배열

        for(var i = 0 ; i < students.length ; i++) {
            students[i] = {}; // 없으면 프로퍼티를 세팅할 수 없어서 에러.
            students[i].name = names[i];
            students[i].kor = getRandomScore();
            students[i].eng = getRandomScore();
            students[i].mat = getRandomScore();
        }
        function getRandomScore() {
            return parseInt(Math.random() * 55 + 46) // 0~54 >> 100 - 54 = 46 
        }
        console.log(students);
        // 총점, 평균 구하는 함수
        for(var i in students) {
            students[i].getSum = function() {
                return this.kor + this.eng + this.mat;
            }
            students[i].getAvg = function() {
                return this.getSum() / 3;
            }
        }
        // 학생 성적 출력
        for(var i in students) {
            document.write("<h3>", "이름: " + students[i].name + 
                ", 총점: " + students[i].getSum() +
                ", 평균: " + students[i].getAvg()
                ,"</h3>")
        }
        // =========== 위 예제랑 구별. 생성자 함수 ============
        document.write("<hr>");
        function Student(name, kor, eng, mat) { // 대문자
            this.name = name;
            this.kor = kor;
            this.eng = eng;
            this.mat = mat;
        }
        // 프로토타입. 이를 통해 생성자 함수로 생성될 객체의 기능을 확장
        // 상속 구현 방법이 존재하지만 실제로 사용되지 않음. (프로토타입이 너무 좋아서)
        Student.prototype.getSum = function() {
            return this.kor + this.eng + this.mat;
        }
        Student.prototype.getAvg = function() {
            return this.getSum() / 3;
        }
        Student.prototype.toString = function() {
            return "이름: " + this.name + 
            ", 총점: " + this.getSum() +
            ", 평균: " + this.getAvg();
        }
        // var student = new Student("윤인성", 90 90 90);
        var students = new Array(names.length);
        for(var i = 0 ; i < students.length ; i++) {
            students[i] = new Student(names[i], getRandomScore(),getRandomScore(),getRandomScore());
            document.write("<h3>", students[i], "</h3>")
        }
    </script>
    <script>
        // 자바스크립트의 캡슐화(자바보다 잘 안 함.)
        var names = ["윤인성", "연하진", "구지연", "나선주", "윤영월", "김미화", "김연화", "박아현", "서준서", ]
        function getRandomScore() {
            return parseInt(Math.random() * 55 + 46)
        }
        function Student(name, kor, eng, mat) {
            var name = name; // 지역변수로 만들고 게터세터
            var kor = kor;
            var eng = eng;
            var mat = mat;
            this.getName = function() {
                return name;
            }
            this.getKor = function() {
                return kor;
            }
            this.getEng = function() {
                return eng;
            }
            this.getMat = function() {
                return mat;
            }
        }

        Student.prototype.getSum = function() {
            return this.getKor() + this.getEng() + this.getMat();
        }
        Student.prototype.getAvg = function() {
            return this.getSum() / 3;
        }
        Student.prototype.toString = function() {
            return "이름: " + this.getName() + 
            ", 총점: " + this.getSum() +
            ", 평균: " + this.getAvg();
        }
    </script>

 

 

- json.html

    <script>
        var names = ["윤인성", "연하진", "구지연", "나선주", "윤영월", "김미화", "김연화", "박아현", "서준서", ]
        function getRandomScore() {
            return parseInt(Math.random() * 55 + 46) // 0~54 >> 100 - 54 = 46 
        }
        // 생성자함수
        function Student(name, kor, eng, mat) { // 대문자
            this.name = name;
            this.kor = kor;
            this.eng = eng;
            this.mat = mat;
        }
        // 프로토타입 정의
        Student.prototype.getSum = function() {
            return this.kor + this.eng + this.mat;
        }
        Student.prototype.getAvg = function() {
            return this.getSum() / 3;
        }
        Student.prototype.toString = function() {
            return "이름: " + this.name + 
            ", 총점: " + this.getSum() +
            ", 평균: " + this.getAvg();
        }
        // 배열생성
        var students = new Array(names.length);
        for(var i = 0 ; i < students.length ; i++) {
            students[i] = new Student(names[i], getRandomScore(),getRandomScore(),getRandomScore());
        }
        // JSON.stringfy 호출
        document.write(JSON.stringify(students));
        // JSON.stringify();    js objct > json string
        // JSON.parse();        json string > js object
    </script>