ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • [자바스크립트] prototype 이용하여 객체(Object) 생성하기
    Front/javascript 2020. 3. 17. 20:56

     

    제목prototype 이용하여 객체(Object) 생성하기


    안녕하세요? 장장스입니다.

     

    자바스크립트는 객체지향 언어입니다. 보통 학교에서 객체지향 프로그램 언어로 JAVA나 CPP 등을 배우죠?(음.. 저는 그랬네요) 자바스크립트는 앞에 말한 언어와는 조금 다른점이 있습니다.

     

     

    prototype 기반의 자바스크립트


    JAVA 혹은 CPP은 클래스(Class)라는 개념이 존재합니다. 그러나 자바스크립트에는 클래스 개념이 없습니다. 대신 프로토타입(prototype) 기반의 객체지향 프로그래밍을 지원합니다.

     

    1. JavaScript의 모든 객체는 '__proto__' 라는 숨겨진 프로퍼티를 갖고 있다.
     __proto__는 자신의 부모인 프로토타입 객체를 가리킨다. 이러한 링크를 'prototype Link'라고 부른다.
    2. JavaScript의 모든 함수는 'prototype' 라는 숨겨진 프로퍼티를 갖고 있다. prototype은 자신에
     new 키워드를 붙여 생성한 객체의 부모를 가리킨다.

     

     

    그렇다면 먼저 자바스크립트에서 객체를 어떻게 만드는지 알아보겠습니다. 자바스크립트는 3가지의 객체 생성 방법을 지원합니다.

     

     

    자바스크립트 객체 생성 방법


    1) 리터럴

    가장 일반적인 방법으로 '{ }' 를 사용하여 객체를 만듭니다.

    var student = {
    
        name: "장장스",
    
        blogAddress: "zangzangs.tistory.com",
    
        birth: "0707"
    
    }

    리터럴로 정의한 객체 student는 name, blogAddress, birth라는 프로퍼티를 갖습니다. 프로퍼티 값으로는 배열, 함수, 객체 등이 올 수 있습니다. (개인적으로 이방법을 가장 많이 쓰게 되는것 같네요 :)

     

     

    2) Object() 생성자 함수

    new 키워드를 이용하여 Object 생성자 함수를 호출하면 빈 객체를 만듭니다.

    var student= new Object();
    
    student.name = "장장스";
    student.blogAddress= "zangzangs.blogspot.com";
    student.birth = "0707";
    
    console.log(student.name)
    console.log(student.blogAddress)
    console.log(student.birth)

    new Object()를 통해 student 객체를 생성해주었습니다.

    '.' 쩜(?)을 통해 프로퍼티를 추가해 줄 수 있습니다.

     

     

    3) 객체 생성자 함수

    내장 객체인 생성자 함수를 사용하여 객체를 생성합니다. 아래 코드는 객체 생성자 함수를 선언하고 객체를 생성하는 기본형입니다.

     

    기본형

    function 함수명(매개변수 1, 매개변수2, … 매개변수 n){
        this.속성명 = 새 값;
        this. 함수명 = function(){
        //#자바스크립트 코드를 입력합니다
        }
    }

    var 참조 변수(인스턴스 네임) = new 함수명();    //객체 생성
    var 참조 변수 = {속성: 새 값, 함수명: function(){ ... }}

     

    new 키워드를 사용해 객체를 생성하고 생성자 함수에서 this 키워드를 사용해 객체에 속성과 함수를 등록합니다.  코드를 보면서 예를 들어 보겠습니다.

    function CheckWeight(name, height, weight){
    
            this.userName = name;
            this.userHeight = height;
            this.userWeight = weight;
            this.minWeight;
            this.maxWeight;
            
            this.getinfo = function(){
                var str =""
                str += "이름: " + this.userName +",";
                str += "키: " + this.userHeight +",";
                str += "몸무게: " + this.userWeight +"<br>";
                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("과체중입니다.");
                }
            }
        }
    
        var jang = new CheckWeight("조이서",162,47);
        var park = new CheckWeight("박새로이",183,78);
    
        console.log(jang);
        console.log(park);

     

    조이서, 박새로이 객체가 각각 생성이 되었네요.

    위에 적은 대로 객체를 생성하면 객체를 생성한 만큼 함수가 등록됩니다. 여기서 한가지 의문이 듭니다. 이렇게 객체를 하나만 생성하면 문제가 되지않겠지만 큰 프로젝트에서 수백 수천개의 객체를 생성해야 한다면 엄청나게 낭비되는 메모리를 어떻게 해야 할까요?

     프로토타입(prototype)을 사용하여 함수를 등록하면 메모리 낭비를 줄일 수 있습니다.

     

    기본형
    function 함수명(매개변수 1, 매개변수2, … 매개변수 n){
        this.속성명 = 값;
    }
       함수명.prototype.함수명= function(){
        //#자바스크립트 코드를 입력합니다.
    }

    var 참조 변수(인스턴스 네임) = new 함수명();

     

     function CheckWeight(name, height, weight){
            this.userName = name;
            this.userHeight = height;
            this.userWeight = weight;
            this.minWeight;
            this.maxWeight;
        }
    
        CheckWeight.prototype.getinfo = function(){
                var str =""
                str += "이름: " + this.userName +",";
                str += "키: " + this.userHeight +",";
                str += "몸무게: " + this.userWeight +"<br>";
                return str;
        }
    
        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("과체중입니다.");
                }
        }
    
        var jang = new CheckWeight("조이서",162,47);
        var park = new CheckWeight("박새로이",183,78);
        
        console.log(jang);
        console.log(park);

    차이가 보이시나요? prototype 함수를 사용하여 선언한 함수 getinfo()와 getResult()가 객체에 등록되지 않았음을 확인할 수 있네요.

     

    객체 생성자 함수를 선언시 prototype  활용하면 메모리 공간을 효율적으로 사용할  있습니다.

     

    지금까지 자바스크립트 prototype을 사용하여 객체 만드는 법에 대해 알아봤습니다!

     

     

    Post


     

     

    References


     

     


    잘못된 코드나 내용이 있다면 댓글을 남겨주세요. 즉시 수정하도록 하겠습니다! :)

     

     

     

    댓글