JavaScript
JS 객체
테라시아
2024. 12. 1. 16:55
Object(객체)
객체의 고유한 속성은 Property라고 부르며
여러 Property(Key-Value의 쌍)으로 표현됨
account = {
name: "Jack",
number: "001234-5678901",
code: "24hour"
}
- account.프로퍼티명
- account['프로퍼티명']
객체는 함수도 가질 수 있으며 이를 메서드라고 부름
account = {
deposit: function(money){
예금 넣으면 할 일;
}
}
account.deposit(10000);
☆ Code
<!doctype html>
<html>
<head>
<title>Object</title>
</head>
<body>
<h1>Javascript Object</h1>
<hr>
</body>
<script>
// create Object 1
var account1 = {
owner: "이선생",
code: "2132",
balance: 36720000,
deposit: function(money){ this.balance += money; },
withdraw: function(money){ this.balance -= money; },
getBalance: function(){ return balance; }
}
// create Object 2
var account2 = new Object();
account2.owner = "바르다김선생";
account2.balance = 50;
account2.deposit = deposit;
function deposit(money){
this.balance += money;
}
account2.deposit(50000);
document.write("<h1>account2.balance : " + account2.balance + "</h1>");
account2.feeling = "Very sad";
account1.feeling = "Very very strawberry happy";
console.log("account1 : " + account1); // String과 같은 줄에 display??
console.log(account1);
// complex(다중 오브젝트)
guest1 = { name: "Devenham", age: 25 }
guest2 = { name: "Conan", age: 10 }
orientExpress = new Object();
orientExpress.passanger1 = guest1;
orientExpress.passanger2 = guest2;
console.log(orientExpress);
document.write("<h1>Passanger1의 이름</h1>");
document.write("<h1>" + orientExpress.passanger1.name + "</h1>");
</script>
</html>