오버로딩 vs 오버라이딩
오버로딩
자바스크립트에는 없는 개념이다. 함수의 매개변수가 자유롭기 때문이다.
하지만 다른 언어에서는
매개변수의 개수
매개변수의 자료형
에 따라 함수를 다르게 선언 할 수 있다.
void overload(){
System.out.println("매개변수 0개");
}
void overload(int i, int j){
System.out.println("매개변수 "+ i + " 그리고 " + j);
}
void overload(double d){
System.out.println("매개변수 " + d);
}
JS에서 위와 같이 하면 같은 이름의 함수를 덮어 쓴다. 따라서 1개의 함수로 여러개의 매개 변수 및 다양한 자료형의 매개변수를 처리하는 기법이 필요하다.
function overload(a, b, c) {
if (typeof c === "function") {
// 문자열 두 개와 콜백
c(a, b);
} else if (typeof b === "function") {
// 옵션 객체와 콜백
b(a);
} else {
// 콜백 하나
a();
}
}
저렇게 쓸일이 없었다..
오버라이딩
객체의 상속받은 부모의 메소드를 재정의하는 것
var Animal = function() {};
Animal.prototype.move = function() {
console.log("동물이 움직여요");
};
var Cat = function() {
Animal.apply(this, arguments); // 속성 상속받는 방법
};
Cat.prototype = Object.create(Animal.prototype); // 프로토타입 상속 방법
Cat.prototype.constructor = Cat; // 버그 패치
console.log(new Animal().move()); // 동물이 움직여요
console.log(new Cat().move()); // 동물이 움직여요
Cat.prototype.move = function(sound) {
// 오버라이딩
console.log(sound + " 움직여요");
return "야옹";
};
console.log(new Cat().move("살금살금")); // 살금살금 움직여요
Last updated
Was this helpful?