Javascript의 Object 생성 방법은 세 가지가 있다
- new Object()이용
- 리터럴 표기법
- 프로토타입
- new Object()이용
12345678910111213141516171819202122232425262728<html><head><title></title><meta charset="utf-8"><script>function deposit(a) {return this.balance += a;}function withdraw(a) {return this.balance -= a;}</script></head><body><h3>new Object()</h3><hr><script>var account = new Object();account.owner = 'KSD';account.code = '1111';account.balance = 400000;account.deposit = deposit;account.withdraw = withdraw;account.deposit(10000);document.write('after deposit balance = ' + account.balance + '<br>');account.withdraw(20000);document.write('after deposit withdraw = ' + account.balance + '<br>');</script></body></html>
cs - 리터럴 표기법
123456789101112131415161718192021222324<html><head><title></title><meta charset="utf-8"></head><body><h3>new Object()_Literal</h3><hr><script>var account = {owner : 'KSD',code : '1111',balance : 400000,deposit : function deposit(a) {return this.balance += a;},withdraw : function withdraw(a) {return this.balance -= a;}}account.deposit(10000);document.write('after deposit balance = ' + account.balance + '<br>');account.withdraw(20000);document.write('after deposit withdraw = ' + account.balance + '<br>');</script></body></html>cs - 프로토타입
12345678910111213141516171819202122232425262728<html><head><title></title><meta charset="utf-8"></head><script>function Account(owner, code, balance){this.owner = owner;this.code = code;this.balance = balance;this.deposit = function deposit(a) {return this.balance += a;}this.withdraw = function withdraw(a) {return this.balance -= a;}}</script><body><h3>new Object()_Prototype</h3><hr><script>var account = new Account('KSD', '1111', 40000);account.deposit(10000);document.write('after deposit balance = ' + account.balance + '<br>');account.withdraw(20000);document.write('after deposit withdraw = ' + account.balance + '<br>');</script></body></html>cs
실행결과 :