arrow function in class
ํด๋์ค์์ arrow function์ ์ค๋ฒ๋ผ์ด๋ฉ ๋ ์ ์๋ค.
๊ธฐ์กด์ ํด๋์ค๋ method ์ ์๋ง ๊ฐ๋ฅํ๋ค. ์ฆ, ํด๋์ค ๋ด๋ถ์ constructor์ method ์ ์๋ก๋ง ํด๋น ํด๋์ค์ ๋ฉ์๋๋ฅผ ์ ์ํ ์ ์๋ค.
https://babeljs.io/docs/en/babel-plugin-proposal-class-properties
ํ์ง๋ง class-properties-proposal ์ ์ฌ์ฉํ๋ฉด 4๊ฐ์ง ๋ฐฉ์์ ํด๋์ค ํ๋กํผํฐ๋ฅผ ์์ฑํ ์ ์๋ค.
class Book {
instanceProperty = 'bork';
boundFunction = () => {
return this.instanceProperty;
};
static staticProperty = 'babeliscool';
static staticFn = function() {
return Bork.staticProperty;
};
}์ด์ ๋ด๊ฐ ํท๊ฐ๋ฆฐ ์ค๋ฒ๋ผ์ด๋ฉ ์์ ๋ฅผ ๋ณด์.
class Animal {
constructor(sound = '??') {
this.sound = sound;
}
setNickname(nickname) {
this.nickname = nickname;
}
arrowNotHerited = () => {
console.log('in Animal');
};
}
class Dog extends Animal {
constructor() {
super('wal wal');
this.species = 'mixed';
}
setNickName(nickname) {
this.nickname = 'doggy_' + nickname;
console.log('overriding fn called');
}
arrowNotHerited() {
console.log('in Dog');
}
}
const baduk = new Dog('urururur');
baduk.setNickname('baduk'); // overriding fn called
baduk.arrowNotHerited(); // in dogarrowNotHerited ๋ฉ์๋๋ ์ค๋ฒ๋ผ์ด๋ฉ ๋์ง ์๋๋ค.
transpile์ ํตํด ๋ฌด์จ์ผ์ด ์ผ์ด๋ฌ๋์ง ์์๋ณด์.
Object.defineProperty ๊ฐ์ฒด์ ์ง์ ์๋ก์ด ์์ฑ์ ์ ์ํ๊ฑฐ๋, ์ด๋ฏธ ์กด์ฌํ๋ ์์ฑ์ ์์ ํ ํ ๊ทธ ๊ฐ์ฒด๋ฅผ ๋ฐํ.
Animal ์์ฑ์ ํจ์์์ arrowNotHerited๋ฅผ ์ง์ ํ ๋น
this๋ ์์ฑ์ ํจ์ ์คํ์ ์์ฑ๋๋ ์ธ์คํด์ค
์ฆ, prototype ๊ฐ์ฒด์ ํ ๋น๋์ง ์๋๋ค.
setNickname์ contructor.prototype์ ํ ๋น
๊ทธ๋ฌ๋ฏ๋ก, setNickname์ ์ค๋ฒ๋ผ์ด๋ฉ์ด ์ ๋์ํ๋ค
์ ์ฝ๋๋ฅผ ๋ฐ๋ฒจ์์ ํธ๋์คํ์ผํ ๊ฒฐ๊ณผ
class ๋ด๋ถ์ ํ์ดํ ํจ์ ์ ์ธ์ standard ๋ฌธ๋ฒ์ด ์๋ค. ๊ทธ๋ฌ๋ฏ๋ก, class-properties ํ๋ฌ๊ทธ์ธ์ ํตํด ์ ์ธํ ์ ์๋ค. ์ด๋ฅผ ์ด์ฉํ์ฌ ํด๋์ค ๋ด๋ถ ํ์ดํ ํจ์ ์ ์ธ์, prototype ๊ฐ์ฒด๊ฐ ์๋ new ์์ฑ์๋ก ์์ฑ๋ ์ธ์คํด์ค์ ํ ๋น๋๋ค.
Animal, Dog ํด๋์ค์ ์์ ์์, new Dog.arrowNotHerited() ํธ์ถ์, ํ๋กํ ํ์ ์ฒด์ด๋์ ํ์ธํ๊ธฐ ์ ์ instance๋ด์ ๋ฉ์๋(arrowNotHerited)๋ฅผ ํธ์ถํ๋ค.
Last updated
Was this helpful?