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

[mdn, ๋“œ๋ฆผ์ฝ”๋”ฉ ์™ธ] ๊ฐ์ฒด์ง€ํ–ฅ (3) : ์ •์  ์†์„ฑ๊ณผ ๋ฉ”์†Œ๋“œ(static properties and methods)

Zoeeey 2022. 5. 4. 12:39

์ •์  ์†์„ฑ๊ณผ ๋ฉ”์†Œ๋“œ(static properties and methods)

static ํ‚ค์›Œ๋“œ๋ฅผ ๋ถ™์ด๋ฉด ํ”„๋กœํผํ‹ฐ๋‚˜ ๋ฉ”์†Œ๋“œ๊ฐ€ ์ธ์Šคํ„ด์Šคํ™”๋˜์ง€ ์•Š๊ณ  ํด๋ž˜์Šค ์ž์ฒด์— ๋ถ™๋Š”๋‹ค.

class goodCoder {
  static codername = 'noran';
  constructor(coderNumber) {
    this.coderNumber = coderNumber;
  }
  
  static printCoder() {
    console.log(goodCoder.codername);
  }
}

const coder1 = new goodCoder(1);
const coder2 = new goodCoder(2);

console.log(coder1.codername); //undefined

์œ„ ์ฝ”๋“œ์—์„œ console.log(coder1.codername);์€ undefined๋ฅผ ๋ฑ‰๋Š”๋‹ค. codername์ด static method์ด๊ธฐ ๋•Œ๋ฌธ์ด๋‹ค.

๊ทธ๋ ‡๊ธฐ ๋•Œ๋ฌธ์— console.log(goodCoder.codername);์œผ๋กœ ํด๋ž˜์Šค๋ช…์œผ๋กœ ๋ถ™์ด๋ฉด ์•„๋ž˜ ์ฝ”๋“œ์ฒ˜๋Ÿผ ๊ฐ’์„ ์ œ๋Œ€๋กœ ๋ฑ‰๋Š”๋‹ค.

console.log(goodCoder.codername); //noran

์–ธ์ œ ์‚ฌ์šฉํ• ๊นŒ?

์˜ค๋ธŒ์ ํŠธ(๋“ค์–ด์˜ค๋Š” ๊ฐ’)์— ์ƒ๊ด€์—†์ด ํด๋ž˜์Šค ๋‚ด์—์„œ ๊ณตํ†ต์ ์œผ๋กœ ์“ธ ์ˆ˜ ์žˆ๋Š” ๊ฒƒ์ด๋ผ๋ฉด static์„ ์“ฐ๋ฉด ๋ฉ”๋ชจ๋ฆฌ๋ฅผ ํšจ๊ณผ์ ์œผ๋กœ ์ค„์ผ ์ˆ˜ ์žˆ๋‹ค.


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