๐ŸŸจ JavaScript/๊ฐœ๋…

[mdn, ๋“œ๋ฆผ์ฝ”๋”ฉ ์™ธ] ๊ฐ์ฒด์ง€ํ–ฅ (1) : ํด๋ž˜์Šค(class)

Zoeeey 2022. 5. 3. 21:07

๋“ค์–ด๊ฐ€๊ธฐ ์•ž์„œ : ์ƒ์„ฑ์žํ•จ์ˆ˜์™€ ํด๋ž˜์Šค์˜ ์ฐจ์ด์ 

https://sunshineyellow.tistory.com/18?category=1037372 

 

[์ฝ”๋”ฉ์•™๋งˆ ์™ธ] ๊ฐ์ฒด ๋ฆฌํ„ฐ๋Ÿด๊ณผ ๊ฐ์ฒด ์ ‘๊ทผ๋ฒ•, ๊ทธ๋ฆฌ๊ณ  ์ƒ์„ฑ์ž ํ•จ์ˆ˜

๊ฐ์ฒด๋ฅผ ์ƒ์„ฑํ•˜๋Š” ๋ฐฉ๋ฒ•์—๋Š” ๋‘ ๊ฐ€์ง€๊ฐ€ ์žˆ๋‹ค. ๊ฐ์ฒด ๋ฆฌํ„ฐ๋Ÿด ์ƒ์„ฑ์ž ํ•จ์ˆ˜ ๋‹จ ํ•˜๋‚˜์˜ ๊ฐ์ฒด๋งŒ์„ ์ƒ์„ฑํ•  ๋•Œ๋Š” ์ง๊ด€์ ์ด๊ณ  ๊ฐ„ํŽธํ•œ ๊ฐ์ฒด ๋ฆฌํ„ฐ๋Ÿด์„ ์‚ฌ์šฉํ•˜๊ณ , ๊ฐ™์€ ๊ฐ์ฒด๋ฅผ ๋Œ€๋Ÿ‰์ƒ์‚ฐํ•  ๋•Œ๋Š” ์ƒ์„ฑ์žํ•จ์ˆ˜๋ฅผ

sunshineyellow.tistory.com

์œ„ ๊ธ€์—์„œ ๊ฐ์ฒด์™€ ์ƒ์„ฑ์žํ•จ์ˆ˜๋ฅผ ๊ฐ„๋‹จํ•˜๊ฒŒ ๊ณต๋ถ€ํ–ˆ๋‹ค.

๊ทธ๋ ‡๋‹ค๋ฉด ์ƒ์„ฑ์žํ•จ์ˆ˜์™€ ๋‹ค๋ฅธ ํด๋ž˜์Šค์˜ ํŠน์ด์ ์€ ๋ฌด์—‡์ผ๊นŒ?

  1. ํด๋ž˜์Šค๋Š” new ์—ฐ์‚ฐ์ž ์—†์ด๋Š” ํ˜ธ์ถœ์ด ๋ถˆ๊ฐ€๋Šฅํ•˜๋‹ค.
  2. ํด๋ž˜์Šค๋Š” extends(ํด๋ž˜์Šค์˜ ์ƒ์†)์™€ super(superํด๋ž˜์Šค์˜ constructor๊ณผ method ํ˜ธ์ถœ)๋ฅผ ์“ธ ์ˆ˜ ์žˆ๋‹ค.
  3. ํด๋ž˜์Šค๋Š” ์ž๋™์œผ๋กœ strict mode๋กœ ์‹คํ–‰๋˜๋ฉฐ ํ˜ธ์ด์ŠคํŒ…์€ ๋˜๋‚˜ TDZ๊ฐ€ ๋ฐœ์ƒํ•ด ์„ ์–ธ ์ „์— ํ˜ธ์ถœํ•  ์ˆ˜ ์—†๋‹ค.

ํด๋ž˜์Šค (class)

ํด๋ž˜์Šค๋Š” ๊ฐ์ฒด๋ฅผ ์ƒ์„ฑํ•˜๊ธฐ ์œ„ํ•œ ํ…œํ”Œ๋ฆฟ์ด๋‹ค.

let Goodcoder = class {
  //constructor
  constructor(name, age) {
    this.name = name;
    this.age = age;
  }
  
  //method
  coding() {
    console.log(`${this.name}, good job!`);
  }
};

ํด๋ž˜์Šค ์•ˆ์—๋Š” ํด๋ž˜์Šค๋กœ ์ƒ์„ฑ๋œ ๊ฐ์ฒด๋ฅผ ์ƒ์„ฑํ•˜๊ณ  ์ดˆ๊ธฐํ™”ํ•  ์ˆ˜ ์žˆ๋Š” ์ƒ์„ฑ์ž(constructor)๊ฐ€ ํ•œ ๊ฐœ๋งŒ ๋“ค์–ด๊ฐˆ ์ˆ˜ ์žˆ๋‹ค. (์—ฌ๋Ÿฌ๊ฐœ์˜ constructor ๋ฉ”์„œ๋“œ๊ฐ€ ๋“ค์–ด๊ฐ€๋ฉด SyntaxError๊ฐ€ ๋ฐœ์ƒํ•œ๋‹ค.)

๋˜ํ•œ method(https://sunshineyellow.tistory.com/17์—์„œ๋„ ๊ณต๋ถ€ํ–ˆ๋‹ค)๊ฐ€ ๋“ค์–ด๊ฐˆ ์ˆ˜ ์žˆ๋‹ค.

ํ•จ์ˆ˜๋ฅผ ์„ ์–ธํ•˜๊ธฐ ์œ„ํ•ด ํ•จ์ˆ˜์„ ์–ธ๋ฌธ๊ณผ ํ•จ์ˆ˜ํ‘œํ˜„์‹์„ ์“ฐ๋“ฏ, ํด๋ž˜์Šค๋ฅผ ์„ ์–ธํ•˜๊ธฐ ์œ„ํ•ด์„œ๋„ ํด๋ž˜์Šค์„ ์–ธ๋ฌธ๊ณผ ํด๋ž˜์Šคํ‘œํ˜„์‹์ด ์žˆ๋‹ค.


ํด๋ž˜์Šค์„ ์–ธ๋ฌธ

class Goodcoder {
  constructor(name, age) {
    this.name = name;
    this.age = age;
  }
}

ํด๋ž˜์Šค์„ ์–ธ๋ฌธ์€ ํ•จ์ˆ˜์„ ์–ธ๋ฌธ๊ณผ ๋‹ค๋ฅด๊ฒŒ ํด๋ž˜์Šค๊ฐ€ ํ˜ธ์ด์ŠคํŒ…๋  ๋•Œ ์ดˆ๊ธฐํ™”๋˜์ง€ ์•Š๊ธฐ ๋•Œ๋ฌธ์— ์„ ์–ธํ•˜๊ธฐ ์ „์— ์‚ฌ์šฉํ•  ์ˆ˜ ์—†๋‹ค.

const noran = new Goodcoder //ReferenceError

class Goodcoder {
  constructor(name, age) {
    this.name = name;
    this.age = age;
  }
}

ํด๋ž˜์Šคํ‘œํ˜„์‹

ํด๋ž˜์Šค์„ ์–ธ๋ฌธ๊ณผ ๋™์ผํ•œ ํ˜ธ์ด์ŠคํŒ…์„ ์ ์šฉ๋ฐ›์•„ ์„ ์–ธํ•˜๊ธฐ ์ „์— ์‚ฌ์šฉํ•  ์ˆ˜ ์—†๋‹ค.

unnamed

let Goodcoder = class {
  constructor(name, age) {
    this.name = name;
    this.age = age;
  }
};

console.log(Goodcoder.name); //Goodcoder๋ฅผ ์ถœ๋ ฅํ•œ๋‹ค.

named

let Goodcoder = class Goodcoder2 {
  constructor(name, age) {
    this.name = name;
    this.age = age;
  }
};

console.log(Goodcoder.name); //Goodcoder2๋ฅผ ์ถœ๋ ฅํ•œ๋‹ค.

name์„ ๊ฐ€์ง„ class์˜ name์€ class body({}๋กœ ๋ฌถ์—ฌ์žˆ๋Š” ๋ถ€๋ถ„)์˜ local scope์— ํ•œํ•ด ์œ ํšจํ•˜๋‹ค.


์ถœ์ฒ˜ : ๋“œ๋ฆผ์ฝ”๋”ฉ https://www.youtube.com/@dream-coding / MDN https://developer.mozilla.org/ko