본문 바로가기

Javascript

Javascript Prototype Pattern

http://weblogs.asp.net/dwahlin/archive/2011/08/01/techniques-strategies-and-patterns-for-structuring-javascript-code-the-prototype-pattern.aspx

위의 기사 내용의 중요한 부분만 발췌하였습니다.

프로토타입 패턴은 크게 2가지의 섹션으로 볼수 있는데 하나는 생성자 섹션이고 다른 하나는 프로토타입 섹션입니다.
프로토타입핑은 객체와 함수 프로퍼트를 연결시켜주는 역할을 합니다.
이것은 인스턴스가 생성되면 모든 프로퍼티와 function을 복사하는 대신 모든 객체에 대해서 하나의 function들과 프로퍼티들이 생성되어 메모리 소비를 절약해 줍니다. 다시말해서 functions과 properties는 하나의 Object단위라기보단 하나의 프로토타입으로 정의됩니다.

럼 본론으로 들어가겠습니다.

Prototype pattern을 사용하기 위해서 먼저 다음같이 생성자 함수를 생성해 줘야합니다. 생성자함수는 하나 이상의 파라미터들을 받을 수 있습니다.  프로토타입에서는 파라미터들이 object범위안에 한정되어있음을 주의해 주세요.

var Calculator = function (tb, eq) {
    this.eqCtl = null;
    this.currNumberCtl = null;
    this.operator = null;
    this.operatorSet = false;
    this.equalsPressed = false;
    this.lastNumber = null;
    this.init(tb, eq);
};

생성자 함수가 정의되면 prototype 키워드를 사용해서 prototype을 생성할수 있습니다.
각 함수에 대해 prototype을 지정해 줄수 있지만 보다 편리하게 json구문을 써서 아래와 같이 표기할수 있습니다. 
 
Calculator.prototype = {

    init: function (tb, eq) {
        this.currNumberCtl = document.getElementById(tb);                
        this.eqCtl = document.getElementById(eq);
    },

    add: function (x, y) {
        return x + y;
    }
}
var calc = null;

위와같이 Prototyped을 만든후 실제적으로 아래와 같이 사용하면 됩니다.

 
window.onload = function () {
    calc = new Calculator('CurrentNumber', 'Equation');
};