티스토리 뷰


JS


오버라이드 (Override)



1. 메서드 오버라이드란?

메서드 오버라이드(override)는 자식 클래스에서 부모 클래스의 기능(method)를 재정의할 때 사용하는 기능입니다. 오버라이드는 두가지 경우에 주로 사용합니다.

경우 1: 부모 클래스의 기능을 사용하지 않고 자식 클래스에서 구현한 기능을 사용하고 싶은 경우

경우 2: 부모 클래스의 기능을 자식 클래스에서 확장하고 싶은 경우



2. 부모 클래스의 기능을 자식 클래스에서 재정의

MyParent.prototype.부모메서드 = function() {}
MyChild.prototype.부모메서드 = function() {}

- 코드 1-1 -


부모 클래스의 기능을 자식 클래스에서 재정의 하고 싶다면 코드 1-1처럼 부모 클래스의 재정의 하고자 하는 기능과 똑같은 이름으로 자식 클래스에서 만들어주면 됩니다.

function MyParent() {
    this.property1 = "data1";
    console.log("MyParent()");
}

MyParent.prototype.method1 = function() {
    console.log("property1 = " + this.property1);
}

function MyChild() {
    console.log("MyChild()");
}
MyChild.prototype = new MyParent();
MyChild.prototype.constructor = MyChild;

// 메소드 오버라이드
MyChild.prototype.method1 = function() {
    console.log("프로퍼티1은 " + this.property1 + "입니다.");
}

var parent = new MyParent();
parent.method1();

var child = new MyChild();
child.method1();

- 코드 1-2 -


코드 1-2는 MyParent를 상속하여 MyChild를 만든후 메소드 오버라이드를 이용하여 method1을 재정의 한 예제 코드입니다.


코드 1-2 실행 결과코드 1-2 실행 결과


코드 1-2 실행 결과를 보면,

첫번째 MyParent() 로그는 MyChild.prototype = new MyParent() 로 출력된 로그 입니다.

두번째 MyParent() 로그는 var parent = new MyParent() 로 출력된 로그 입니다.

세번째 property1 = data1 로그는 parent.method1()의 결과로 출력된 로그 입니다.

네번째 MyChild() 로그는 var child = new MyChild() 로 출력된 로그 입니다.

다섯번째 프로버티1은 data1입니다. 로그는 메소드 오버로드로 재정의 되어 출력된, child.method1의 결과값입니다.



3. 부모 클래스의 기능을 자식 클래스에서 확장

부모의 기능을 그대로 사용하면서 동시에 기능을 약간 추가하고 싶은 경우에도 메소드 오버라이드를 활용합니다.

MyChild.prototype.부모매소드 = function([param1, param2, ...]) {
    부모클래스.prototype.부모메소드.call(this[, param1, param2, ...]);
    // 추가 확장 구문
}

- 코드 2-1 -


기본은 오버라이드하고자 하는 부모 클래스의 함수을 자식 클래스에서 동일한 이름으로 만들어 주는 것입니다. 이후 이후 함수 내부에는 call 함수를 황욯애 부모 기능을 호출해 줍니다. (call 함수 사용법은 [자바스크립트] API - call, apply 함수 참고)

function MyParent() {
    this.property1 = "data1";
    console.log("MyParent()");
}

MyParent.prototype.method1 = function() {
    console.log("property1 = " + this.property1);
}

function MyChild() {
    console.log("MyChild()");
    this.property2 = "data2";
}
MyChild.prototype = new MyParent();
MyChild.prototype.constructor = MyChild;

// 메소드 오버라이드
MyChild.prototype.method1 = function() {
    MyParent.prototype.method1.call(this)
    console.log("프로퍼티2는 " + this.property2 + "입니다.");
}

var child = new MyChild();
child.method1();

- 코드 2-2 -


코드 2-2는 MyParent를 상속하여 MyChild를 만든후 메소드 오버라이드를 이용하여 method1을 확장한 예제 코드입니다


코드 2-2 실행 결과코드 2-2 실행 결과


코드 2-2 실행 결과를 보면,

첫번째 MyParent() 로그는 MyChild.prototype = new MyParent() 로 출력된 로그 입니다.

두번째 MyChild() 로그는 var child = new MyChild() 로 출력된 로그 입니다.

세번째 property1 = data1 로그는 MyParent.prototype.method1.call(this)로 출력된 부모 클래스의 method1의 결과값입니다.

네번째 프로퍼티2는 data2입니다. 로그는 console.log로 출력된 확장된 로그 입니다.



오버로딩 (Overloading)



자바스크립트는 문법적으로 오버로딩을 제공하지 않습니다. 대신 오버로딩을 흉내 낼 수 있는데, 매개변수 정보를 담수 있는 arguments를 이용해 오버로딩을 흉내낼 수 있습니다.

function sum() {
    var stringResult = '';
    var numberResult = 0;

    for(var i = 0; i < arguments.length; i++) {
        if (typeof(arguments[i]) == "string") {
            stringResult += arguments[i] + ",";
        } else if (typeof(arguments[i]) == "number") {
            numberResult += arguments[i];
        }
    }
    if (stringResult != '') {
        return stringResult;
    } else {
        return numberResult;
    }
}

console.log(sum(1, 2));
console.log(sum(1, 2, 3));
console.log(sum("가", "나"));

- 코드 3 -


코드 3 실행 결과코드 3 실행 결과


파라미터가 여러개 일 경우, 혹은 변수 타입의 종류가 다를 경우 코드 3과 같이 arguments를 이용하여 오버로딩 할 수 있습니다.






(참조 문헌 : 자바스크립트 + JQuery 완전정복 스터디)

댓글
공지사항
최근에 올라온 글