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 dog

arrowNotHerited ๋ฉ”์„œ๋“œ๋Š” ์˜ค๋ฒ„๋ผ์ด๋”ฉ ๋˜์ง€ ์•Š๋Š”๋‹ค.

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?