블로그 보관함

2014년 3월 10일 월요일

JavaScript 19 prototype 함수의 이용

함께 묶은 함수 및 변수들을 커다란 한 개의 함수처럼 만들어 준 후에 자주 사용하는 내장 함수들에 대해서 각각의 함수에서 사용하지 않고 공통의 공간에서 처리할 수 있도록 prototype이라는 별도의 공간에 정의하여 불 필요한 메모리 낭비를 줄일 수 있도록 만들어 주었다.



html

<script>
"use strict";
// 3 * 2 + 7 - 5 = ?
// 5 - 4 * 2 / 9 = ?
var calc1 = new Calculator();
var calc2 = new Calculator();
calc1.init(3);
calc2.init(5);
calc1.multiple(2);
calc2.minus(4);
calc1.plus(7);
calc2.multiple(2);
calc1.minus(5);
calc2.divide(9);
calc1.printResult();
calc2.printResult();

/* var number, op;
number = prompt('input number');
init(number);
op = prompt('input operand');
switch(op){
case +:
plus()
}
printResult(); */
</script>


js -------------------------------------------------------------------------------

function Calculator() {
this.sum = 0;
this.str = '';
}
Calculator.prototype.plus = function(value) {
this.sum += value;
this.str += ' + ' + String(value);
};
Calculator.prototype.minus = function(value) {
this.sum -= value;
this.str += ' - ' + String(value);
};
Calculator.prototype.multiple = function(value) {
this.sum *= value;
this.str += ' * ' + String(value);
};
Calculator.prototype.divide = function(value) {
this.sum /= value;
this.str += ' / ' + String(value);
};
Calculator.prototype.init = function(value) {
if (arguments.length == 0) {
this.sum = 0;
this.str = '';
} else {
this.sum = value;
this.str += String(value);
}
};
Calculator.prototype.printResult = function() {
console.log(this.str, '=', this.sum);
};

댓글 없음:

댓글 쓰기