๋ณธ๋ฌธ ๋ฐ”๋กœ๊ฐ€๊ธฐ

๐Ÿ“ฐ ์–ธ์–ด/JS - ๋น„๊ธฐ๋„ˆ ํŽธ

ES6 - class

MDN_Classes >

 

function ์˜ค๋ธŒ์ ํŠธ๋ฅผ ์ƒ์„ฑํ•˜๋Š” ๋ชฉ์ 

๊ทธ์ € function ์˜ค๋ธŒ์ ํŠธ ๊ฐœ๋…์œผ๋กœ ์‚ฌ์šฉํ•˜๊ฑฐ๋‚˜ ๋˜๋Š” ํด๋ž˜์Šค ๊ฐœ๋…์œผ๋กœ ์‚ฌ์šฉํ•˜๊ธฐ ์œ„ํ•ด์„œ function ์˜ค๋ธŒ์ ํŠธ๋ฅผ ์ƒ์„ฑํ•˜์˜€๋‹ค.

# ํ”„๋กœํ† ํƒ€์ž…์— ๋ฉ”์†Œ๋“œ๋ฅผ ์ž‘์„ฑ X => ๊ทธ์ € function ์˜ค๋ธŒ์ ํŠธ ๊ฐœ๋…
var book = function(){};

# ํ”„๋กœํ† ํƒ€์ž…์— ๋ฉ”์†Œ๋“œ ์ž‘์„ฑ O => ํด๋ž˜์Šค ๊ฐœ๋…
var Book = function(){};
Book.prototype.getBook = function(){};

ES6์ด์ „์˜ ์ž๋ฐ”์Šคํฌ๋ฆฝํŠธ๋Š” prototype์— ๋ฉ”์†Œ๋“œ๋ฅผ ์—ฐ๊ฒฐํ•˜์—ฌ ํด๋ž˜์Šค ๊ฐœ๋…์„ ์‚ฌ์šฉํ•˜์˜€๋‹ค. ํ•˜์ง€๋งŒ, ES6๋ถ€ํ„ด classํ‚ค์›Œ๋“œ๊ฐ€ ์ถ”๊ฐ€๋˜๋ฉด์„œ classํ‚ค์›Œ๋“œ๋ฅผ ์ด์šฉํ•˜์—ฌ ํด๋ž˜์Šค๋ฅผ ์ƒ์„ฑํ•  ์ˆ˜ ์žˆ๋‹ค.

 

class

1. class

  • class๋Š” ์‚ฌ์‹ค ํŠน๋ณ„ํ•œ ํ•จ์ˆ˜์ด๊ธฐ ๋•Œ๋ฌธ์— ํ•จ์ˆ˜๋ฅผ ํ•จ์ˆ˜ ํ‘œํ˜„์‹๊ณผ ํ•จ์ˆ˜ ์„ ์–ธ์œผ๋กœ ์ •์˜ํ•  ์ˆ˜ ์žˆ๋“ฏ์ด class๋ฌธ๋ฒ•๋„ classํ‘œํ˜„์‹๊ณผ class์„ ์–ธ ๋‘ ๊ฐ€์ง€ ๋ฐฉ๋ฒ•์„ ์ œ๊ณตํ•œ๋‹ค.
  • ์ž๋ฐ”์Šคํฌ๋ฆฝํŠธ๋Š” prototype์— ๋ฉ”์†Œ๋“œ๋ฅผ ์—ฐ๊ฒฐํ•˜์—ฌ ์ž‘์„ฑํ•œ๋‹ค. ES6์—์„œ๋Š” class์— ๋ฉ”์†Œ๋“œ๋ฅผ ์ž‘์„ฑํ•˜์—ฌ ํด๋ž˜์Šค๋ฅผ ์ƒ์„ฑํ•  ์ˆ˜ ์žˆ๋‹ค. ํ•˜์ง€๋งŒ, ๋‚ด๋ถ€์—์„œ๋Š” prototype์— ์—ฐ๊ฒฐํ•˜๋Š” ๊ณผ์ •์ด ์ผ์–ด๋‚œ๋‹ค.
  • ํด๋ž˜์Šค์˜ body๋ถ€๋ถ„์€ strict mode์—์„œ ์‹คํ–‰๋œ๋‹ค. ๊ทธ๋ ‡์ง€ ์•Š์œผ๋ฉด ์กฐ์šฉํžˆ ์˜ค๋ฅ˜๊ฐ€ ๋ฐœ์ƒํ•  ์ˆ˜ ์žˆ๊ธฐ ๋•Œ๋ฌธ์ด๋‹ค.

 

1) class ์„ ์–ธ

class๋ฅผ ์„ ์–ธํ•˜๊ธฐ ์œ„ํ•ด์„œ class ํ‚ค์›Œ๋“œ์™€ ํ•จ๊ป˜  ํด๋ž˜์Šค๋ช…๋ฅผ ์‚ฌ์šฉํ•œ๋‹ค.

class Rectangle {
  constructor(height, width) {
    this.height = height;
    this.width = width;
  }
}

 

2) class ํ‘œํ˜„์‹

 Class ํ‘œํ˜„์‹์€ ์ด๋ฆ„์„ ๊ฐ€์งˆ ์ˆ˜๋„ ์žˆ๊ณ , ๊ฐ–์ง€ ์•Š์„ ์ˆ˜๋„ ์žˆ๋‹ค.

์ด๋ฆ„์„ ๊ฐ€์ง„ class ํ‘œํ˜„์‹์˜ ์ด๋ฆ„์€ ํด๋ž˜์Šค body์˜ local scope์— ํ•œํ•ด ์œ ํšจํ•˜๋‹ค. 

# unnamed
let Rectangle = class {
  constructor(height, width) {
    this.height = height;
    this.width = width;
  }
};
console.log(Rectangle.name);
// ์ถœ๋ ฅ: "Rectangle"

# named
let Rectangle = class Rectangle2 {
  constructor(height, width) {
    this.height = height;
    this.width = width;
  }
};
console.log(Rectangle.name);
// ์ถœ๋ ฅ: "Rectangle2"