728x90
반응형
객체 생성자 함수를 선언하고 객체를 생성하는 기본형입니다.
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 + "<br>";
str += "키:" + this.userHeight + "<br>";
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 choi = new CheckWeight("최민준", 180, 85);
var jung = new CheckWeight("정하나", 168, 56);
console.log(choi);
console.log(jung);
document.write(choi.getInfo());
document.write(choi.getResult());
결과 값입니다
콘솔 화면에서 등록된 속성과 함수도 확인할 수 있습니다.
프로토타입(prototype)
여러개의 함수를 등록할 필요가 없어서 메모리 낭비를 줄일 수 있습니다.
아래는 프로토 타입으로 객체를 생성할 때 함수를 등록하는 기본형 입니다.
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 + "<br>";
str += "키:" + this.userHeight + "<br>";
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 choi = new CheckWeight("최민준", 180, 85);
var jung = new CheckWeight("정하나", 168, 56);
console.log(choi);
console.log(jung);
document.write(choi.getInfo());
document.write(choi.getResult());
document.write(choi.getResult === jung.getResult);
이전에 했던 결과값과는 달리 객체에 함수가 등록되지 않았습니다.
728x90
반응형
'IT > JavaScript' 카테고리의 다른 글
[javaScript] 함수2 (1) | 2020.01.11 |
---|---|
[javaScript] 함수1 (0) | 2019.12.30 |
[javascript] 브라우저모델 BOM (0) | 2019.12.30 |
[javascript] - 내장객체(문자열) (0) | 2019.12.26 |
[javascript] - 내장객체(배열) (0) | 2019.12.25 |
댓글