개발자의 길/Javascript
자바스크립트 메소드(Method)
모쿠
2017. 4. 6. 09:45
<자바스크립트의 객체가 가지고 있는 함수>
- 함수를 이용하여 정보 출력
<18_method.html>
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 | <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>JavaScript</title> </head> <body> <h1>JavaScript Method: 객체가 가지고 있는 함수</h1> <div id="output"></div> <script> var output = document.getElementById('output'); // 생성자 함수 function Unit(money, gas, ph) { /* property */ this.money = money; this.gas = gas; this.ph = ph; /* method */ this.attack = function(unit) { unit.ph -= 10; output.innerHTML += unit.ph + '<br/>' }; this.toString = function() { // 유닛의 money, gas, ph를 문자열로 리턴 // money: xx, gas: yy, ph : zz 형식 return 'money: ' + money + ', ' + 'gas: ' + gas + ', ' + 'ph: ' + ph; }; } var zilot = new Unit(100, 0, 60); var marine = new Unit(50, 0, 40); zilot.attack(marine); zilot.attack(marine); output.innerHTML += '유닛 정보 - ' + marine.toString() + '<br/>'; </script> </body> </html> | cs |
<출력화면>