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
Was this helpful?