본문 바로가기
💻 1. 웹개발_Front end/1-4 Javascript

[Javascript] 05-4 객체 생성자 함수의 활용

by 달님🌙 2021. 9. 12.
반응형

 

객체 생성자 함수

 

1. 의미 : 내장 객체를 생성할 때는 이미 자바스크립트 엔진에 내장되어 있는 객체 생성자 함수(Object Constructor Function)를 사용하여 객체를 생성

 

2. 기본형 

<script>
	function 함수명(매개변수1, 매개변수2, ..., 매개변수n) {
		this.속성명 = 새 값;
		this.함수명 = function() {
        	자바스크립트 코드;
		}
	}
    var 참조 변수(인스턴스 네임) = new 함수명(); // 객체 생성
    var 참조 변수 = {속성 : 새 값, 함수명 : function(){ ... }}
</script>

 

3. 예제 - 몸무게 정상 여부 출력

<!DOCTYPE html>
<html lang="ko">
<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>객체 생성자 함수</title>
</head>
<body>
    <script>
        function checkWeight(name, weight, height) {
            //this는 checkWeight라는 객체를 가르킴.
            this.userName = name;
            this.userWeight = weight;
            this.userHeight = height;
            this.minWeight;
            this.maxWeight;

            this.getInfo = function() {
                var str = "";
                str += "이름 : " + this.userName + ", "; 
                str += "몸무게 : " + this.userWeight + ", ";
                str += "신장 : " + this.userHeight;
                return str;
            } 
            this.getResult = function() {
                this.minWeight = (this.userHeight - 100) * 0.9 - 5;
                this.maxWeight = (this.userHeight - 100) * 0.9 + 5;

                if(this.userWeight >= this.minWeight && this.userWeight <= this.maxWeight) {
                    return "정상 몸무게 입니다.";
                } else if(this.userWeight <= this.minWeight) {
                    return "정상 몸무게보다 미달입니다.";
                } else {
                    return "정상 몸무게보다 초과입니다.";
                }
            }
        }

        //checkWeight객체 생성
        var jang = new checkWeight("장보리", 62, 168);
        //checkWeight객체 생성
        var park = new checkWeight("박달재", 88, 180);
        console.log(jang);
        console.log(park);

        document.write(jang.getInfo(), "<br>");
        document.write(jang.getResult(), "<br><br>");
        document.write(park.getInfo(), "<br>");
        document.write(park.getResult(), "<br><br>");
    </script>
</body>
</html>

 

 

메모리 절약을 위한 프로토타입 사용하기

 

1. 의미 : 앞에서 배운 대로 객체를 생성하면 객체를 생성한 만큼 함수가 등록되어 메모리 낭비를 하게 된다.

객체 생성자 함수에 프로토타입을 사용하여 함수를 등록하면 메모리 낭비를 줄일 수 있음

 

 

2. 기본형

<script>
	function 함수명(매개변수1, 매개변수2, ..., 매개변수n) {
    	this.속성명 = 새 값;
    }
    함수명.prototype.함수명 = function() {
    	자바스크립트 코드;
    }
    
    var 참조변수(인스턴스 네임) = new 함수명();
</script>

 

3. 예제 - 객체를 생성할 때 프로토타입으로 함수를 등록하기

<script>
        function checkWeight(name, weight, height) {
            //this는 checkWeight라는 객체를 가르킴.
            this.userName = name;
            this.userWeight = weight;
            this.userHeight = height;
            this.minWeight;
            this.maxWeight;

            //checkWeight 
            checkWeight.prototype.getInfo = function() {
                var str = "";
                str += "이름 : " + this.userName + ", "; 
                str += "몸무게 : " + this.userWeight + ", ";
                str += "신장 : " + this.userHeight ;
                return str;
            } 

            //checkWeight의 프로토타입
            checkWeight.prototype.getResult = function() {
                this.minWeight = (this.userHeight - 100) * 0.9 - 5;
                this.maxWeight = (this.userHeight - 100) * 0.9 + 5;

                if(this.userWeight >= this.minWeight && this.userWeight <= this.maxWeight) {
                    return "정상 몸무게 입니다.";
                } else if(this.userWeight <= this.minWeight) {
                    return "정상 몸무게보다 미달입니다.";
                } else {
                    return "정상 몸무게보다 초과입니다.";
                }
            }
        }

        //checkWeight객체 생성
        var jang = new checkWeight("장보리", 62, 168);
        //checkWeight객체 생성
        var park = new checkWeight("박달재", 88, 180);
        console.log(jang);
        console.log(park);

        document.write(jang.getInfo());
        document.write(jang.getResult(), "<br>");
        //프로토타입의 메소드 호출 -> 객체마다 메소드 호출할 필요가 없어져서 메모리가 절약됨
        document.write(jang.getResult === park.getResult); // true 두 객체가 같은 함수를 사용
    </script>

* 위 예제의 결과와 달리 함수들은 console에 찍히지않은 것을 알 수 있다. 

 

 

반응형

댓글