javascript
객체 생성자 함수_프로토타입(prototype)
신방동불주먹
2022. 11. 15. 12:54
반응형
- java의 static 개념과 같음
- 메소드를 공유
- 메모리 효율성을 위함
<객체 생성자 함수>
<script>
function CheckWeight(name, height, weight){
this.name=name;
this.height=height;
this.weight=weight;
this.minWeight;
this.maxWeight;
this.getInfo = function(){
var str="";
str += "이름 : " + this.name + ", ";
str += "키 : " + this.height + ", ";
str += "몸무게 : " + this.weight;
return str;
}
this.getResult = function(){
this.minWeight=(this.height - 100) * 0.9 -5;
this.maxWeight=(this.weight -100) * 0.9 +5;
if(this.weight >= this.minWeight && this.weight <= this.maxWeight){
return "정상몸무게 입니다.";
}else if (this.weight < this.minWeight){
return "몸무게 미달입니다."
}else{
return "몸무게 초과입니다."
}
}
}
var limi = new CheckWeight("리미", 168, 59);
var bini = new CheckWeight("비니", 181, 80);
console.log(limi);
console.log(bini);
</script>
<prototype>
- 메소드를 생성자 함수 밖으로 빼낸다
- this가 아닌 객체 생성자명.prototype.함수명을 사용
<script>
function CheckWeight(name, height, weight){
this.name=name;
this.height=height;
this.weight=weight;
this.minWeight;
this.maxWeight;
}
CheckWeight.prototype.getInfo = function(){
var str="";
str += "이름 : " + this.name + ", ";
str += "키 : " + this.height + ", ";
str += "몸무게 : " + this.weight;
return str;
}
CheckWeight.prototype.getResult = function(){
this.minWeight=(this.height - 100) * 0.9 -5;
this.maxWeight=(this.weight -100) * 0.9 +5;
if(this.weight >= this.minWeight && this.weight <= this.maxWeight){
return "정상몸무게 입니다.";
}else if (this.weight < this.minWeight){
return "몸무게 미달입니다."
}else{
return "몸무게 초과입니다."
}
}
var limi = new CheckWeight("리미", 168, 59);
var bini = new CheckWeight("비니", 181, 80);
console.log(limi);
console.log(bini);
console.log(limi.getInfo(), limi.getResult());
console.log(bini.getInfo(), bini.getResult());
</script>
반응형