Web - Front end 20. Javascript 사용자 객체 만들기
JavaScript에서 제공하는 코어객체 외에 새로운 타입의 객체를 사용자가 만들어 사용할 수 있음
프로토타입(prototype) : 개발자가 선언하는 새로운 객체 타입
3가지 방법으로 사용자 객체 생성 가능
1. new Object()로 객체 생성
'new Object()' 로 프로퍼티가 없는 빈 객체를 만들고 프로퍼티와 메소드를 추가
프로퍼티 추가시 이름과 함께 값을 줘야함
- 객체와 프로퍼티 선언
let account = new Object(); // account 객체 생성
account.owner = "Tom"; // 프로퍼티 owner 생성 및 초기화
account.code = "111"; // 프로퍼티 code 생성 및 초기화
account.balance = 35000; // 프로퍼티 balance 생성 및 초기화
- 프로퍼티 사용
객체["프로퍼티"] or 객체.프로퍼티
let name = account["owner"]; // name = "Tom"
account["balance"] = 10000; // balance 프로퍼티에 값 10000 저장
account.balance += 20000; // balance 프로퍼티에 + 20000
- 메소드 만들기
메소드 이름과 동일한 이름의 함수 생성
객체의 메소드 이름을 함수 이름으로 초기화 (메소드와 함수 뒤에 ( ) 를 붙이지 않는다.)
function deposit(money) { // 메소드로 사용할 함수 작성
this.balance += money; // 객체(this)의 프로퍼티 balance에 money 더하기
}
account.deposit = deposit; // 메소드 deposit을 함수 deposit으로 초기화
this는 이 객체를 의미하며 this.balance는 이 객체의 balance 프로퍼티를 뜻함. this 없이 balance만 선언했으면 balance를 프로퍼티가 아닌 전역변수나 지역변수로 인식
객체의 맴버변수인 프로퍼티에 접근할 때는 반드시 this. 사용
* 예시 - 'new Object' 키워드를 이용한 은행 계좌 객체 생성 및 사용
<head>
<script>
//함수 정의
function inquiry(){ // 잔액 확인
return this.balance
}
function deposit(money){ // 입금
this.balance += money;
}
function withdraw(money){ // 출금
this.balance -= money;
return money;
}
//객체 생성
let account = new Object();
//프로퍼티 생성
account.owner = "Tom";
account.code = "111-33-7-888";
account.balance = 10000;
//메소드 연결
account.inquiry = inquiry;
account.deposit = deposit;
account.withdraw = withdraw;
</script>
</head>
<body>
<script>
document.write("<h1>계좌정보</h1>");
document.write("<h3>성명 : " + account.owner + "</h3>");
document.write("<h3>계좌번호 : " + account.code + "</h3>");
document.write("<h3>잔액 : " + account.balance + "원</h3>");
// 예금
account.deposit(50000);
document.write("50000원 예금<br>");
// 잔액 확인
document.write("잔액 : " + account.inquiry() + "<br>");
// 인출
account.withdraw(30000)
document.write("30000원 인출<br>");
document.write("잔액 : " + account.inquiry());
</script>
</body>
2. 리터럴 표기법으로 객체 생성
중괄호({ })를 이용하여 프로퍼티와 메소드를 한 번에 작성 -> 리터럴 표기법
메소드와 프로퍼티가 블록 안에 모두 만들어지기 때문에 가독성이 높음
'프로퍼티 or 메소드 이름 : 내용' 형식
중괄호 안의 프로퍼티와 메소드들은 콤마(,)로 구분
* 예시 - 리터럴 표기법을 이용한 은행 계좌 객체 생성 및 사용
<head>
<script>
//객체 생성
let account = {
//프로퍼티 생성
owner : "Tom",
code : "111-33-7-888",
balance : 10000,
//메소드 정의
inquiry : function (){ // 잔액 확인
return this.balance
},
deposit : function (money){ // 입금
this.balance += money;
},
withdraw : function (money){ // 출금
this.balance -= money;
return money;
}
};
</script>
</head>
<body>
<script>
document.write("<h1>계좌정보</h1>");
document.write("<h3>성명 : " + account.owner + "</h3>");
document.write("<h3>계좌번호 : " + account.code + "</h3>");
document.write("<h3>잔액 : " + account.balance + "원</h3>");
// 예금
account.deposit(50000);
document.write("50000원 예금<br>");
// 잔액 확인
document.write("잔액 : " + account.inquiry() + "<br>");
// 인출
account.withdraw(30000)
document.write("30000원 인출<br>");
document.write("잔액 : " + account.inquiry());
</script>
3. 프로토타입(class) 개념
C언어나 Java, Python 등의 언어에서 class의 개념이 JavaScript에서는 프로토타입
개발자가 프로토타입을 만들고 new 연산자로 객체를 생성해서 활용 가능
위의 두 방식과는 다르게 동일한 속성의 객체를 여러개 생성할 때 유용
* 프로토타입은 함수로 생성
프로토타입은 함수로 작성해서 함수를 호출하면 해당 객체가 생성됨
프로토타입을 만들 때 사용하는 함수를 생성자 함수(constructor)라고 함
new 키워드로 객체가 생성될 때 호출됨
JavaScript 에서 제공하는 Array, String 등의 객체들도 함수로 만들어져 있음
객체를 생성할 때는 new 키워드와 함께 생성자 함수를 호출하고 매개변수로 프로퍼티들의 값을 지정해 줌
* 예제 - 프로토타입을 이용한 은행 계좌 객체 생성 및 사용
<head>
<script>
// 프로토타입 Account 생성
function Account(owner, code, blance){
this.owner = owner;
this.code = code;
this.balance = balance;
//메소드 정의
this.inquiry = function (){ // 잔액 확인
return this.balance
}
this.deposit = function (money){ // 입금
this.balance += money;
}
this.withdraw = function (money){ // 출금
this.balance -= money;
return money;
}
}
</script>
</head>
<body>
<script>
// 객체 생성
let account = new Account("Tom", "111-33-7-888", 30000);
document.write("<h1>계좌정보</h1>");
document.write("<h3>성명 : " + account.owner + "</h3>");
document.write("<h3>계좌번호 : " + account.code + "</h3>");
document.write("<h3>잔액 : " + account.balance + "원</h3>");
// 예금
account.deposit(30000);
document.write("30000원 예금<br>");
// 잔액 확인
document.write("잔액 : " + account.inquiry() + "<br>");
// 인출
account.withdraw(20000)
document.write("20000원 인출<br>");
document.write("잔액 : " + account.inquiry());
</script>
</body>

댓글
댓글 쓰기