Overriding

์˜ค๋ฒ„๋กœ๋”ฉ(Overloading)์€ ๊ฐ™์€ ์ด๋ฆ„, ๋‹ค๋ฅธ ๋งค๊ฐœ๋ณ€์ˆ˜๋ฅผ ๊ฐ€์ง„ ๋ฉ”์†Œ๋“œ๊ฐ€ ์—ฌ๋Ÿฌ ๊ฐœ ์กด์žฌํ•˜๋Š” ๊ฒƒ์„ ๋งํ•œ๋‹ค. ๋งค๊ฐœ๋ณ€์ˆ˜๊ฐ€ ๋‹ค๋ฅด๋ฉด ๋‹ค๋ฅธ ๋ฉ”์†Œ๋“œ์ž„์„ ์•Œ ์ˆ˜ ์žˆ๊ธฐ ๋•Œ๋ฌธ์— ๊ฐ€๋Šฅํ•œ ๊ธฐ๋Šฅ์ธ๋ฐ, ์ž๋ฐ”์Šคํฌ๋ฆฝํŠธ์—์„œ๋Š” ๊ธฐ๋ณธ์ ์œผ๋กœ ๋ถˆ๊ฐ€๋Šฅํ•˜๋‹ค. (๋Œ€์‹  ๋งค๊ฐœ๋ณ€์ˆ˜์˜ ์กด์žฌ ์—ฌ๋ถ€์— ๋”ฐ๋ผ ๋ถ„๊ธฐ๋ฅผ ๋‚˜๋ˆ„๋Š” ๋ฐฉ์‹์œผ๋กœ ๊ตฌํ˜„ํ•  ์ˆ˜๋Š” ์žˆ๋‹ค.) ํ•œ ํด๋ž˜์Šค ์•ˆ์— ๊ฐ™์€ ์ด๋ฆ„์„ ๊ฐ€์ง„ ๋ฉ”์†Œ๋“œ๊ฐ€ ์—ฌ๋Ÿฌ ๊ฐœ ์กด์žฌํ•  ์ˆ˜ ์—†์œผ๋ฉฐ, constructor๋„ ๋ฐ˜๋“œ์‹œ ํ•˜๋‚˜๋งŒ ์žˆ์–ด์•ผ ํ•œ๋‹ค.

์˜ค๋ฒ„๋ผ์ด๋”ฉ(Overriding)์€ subclass๊ฐ€ superclass์˜ ๋ฉ”์†Œ๋“œ๋ฅผ ๋ฎ์–ด์“ฐ๋Š” ๊ฒƒ์„ ๋งํ•œ๋‹ค. ๋จผ์ € Foodํด๋ž˜์Šค์— makeNoise() ๋ฉ”์†Œ๋“œ๋ฅผ ์ถ”๊ฐ€ํ–ˆ๋‹ค.

// Food.js
class Food{
    constructor(name) {
        this.name = name;
    }
    
    getName() {
        return this.name;
    }
    
    makeNoise() {
        console.log('It makes a noise');
    }
}

export default Food;

Deep ํด๋ž˜์Šค์— ๊ฐ™์€ ์ด๋ฆ„์˜ ๋ฉ”์†Œ๋“œ makeNoise()๋ฅผ ์ •์˜ํ–ˆ๋‹ค.

// Deep.js
import Food from './Food';

class Deep extends Food{
    constructor(name) {
        super(name);
    }
    
    // Override
    makeNoise() {
        console.log('Bark!');
    }
}

export default Deep ;

Foodํด๋ž˜์Šค์˜ makeNoise()๊ฐ€ Deep ํด๋ž˜์Šค์˜ makeNoise()๋กœ ์˜ค๋ฒ„๋ผ์ด๋“œ๋œ ๊ฒƒ์„ ๋ณผ ์ˆ˜ ์žˆ๋‹ค.

// index.js
import Deep from './Deep';

let jake = new Deep('Jake');

console.log(jake.getName()); // 'Jake'
jake.makeNoise(); // ์˜ค๋ฒ„๋ผ์ด๋“œ๋œ ๊ฒฐ๊ณผ 'Bark!' 

Last updated