티스토리 뷰

-객체 생성자 함수의 활용

내장 객체를 생성할 때는 이미 자바스크립트 엔진에 내장되어 있는 객체 생성자 함수를 사용하여 객체를 생성한다.

 

기본형 | function 함수명(매개변수1,매개변수2,...매개변수n)   {        //객체 생성자 함수

            this.속성명=새 값;

            this.함수명=function() {

            자바스크립트 코드;

            }

    }

            var 참조 변수 (인스턴스 네임) = new 함수명();                      //객체생성

            var 참조 변수=(속성: 새 값,함수명:function() {

...

}

 }

ex)

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("포맨",168,62);
var park=new checkWeight("홍길동",183,73);
console.log(jang);
console.log(wark);

document.write(jang.getInfo()); //객체 생성
document.write(wark.getResult()); //객체 생성


-메모리 절약을 위한 프로토 타입

앞 예제에선 객체를 생성한 만큼 함수가 등록이 된다. 그에따라 메모리 낭비도 심해진다. 이럴 때 객체 생성자 함수에 프로토타입(Prototype)을 사용하여 함수를 등록하면 메모리 낭비를 줄일 수 있다.

 

기본형         |         function 함수명 (매개변수 1, 2, .. n) {        

                             this.속성명 = 새 값;

            }

                           함수명.prototype. 함수명 = function () {

                           자바스크립트 코드;

               }

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