๐Ÿ“˜ TypeScript/๊ฐœ๋…

[์ฝ”๋”ฉ์• ํ”Œ] ํƒ€์ž…์Šคํฌ๋ฆฝํŠธ์—์„œ์˜ class : constructor, prototype ํƒ€์ž…์ง€์ •

Zoeeey 2023. 12. 20. 19:17

ํƒ€์ž…์Šคํฌ๋ฆฝํŠธ์—์„œ class์˜ constructor ์‚ฌ์šฉํ•˜๊ธฐ

์ผ๋ฐ˜์ ์ธ JavaScript ํด๋ž˜์Šค ๋ฐ ๊ฐ์ฒด ์ƒ์„ฑ์˜ ์˜ˆ์‹œ์ด๋‹ค.

// JavaScript
class Candidate {
  constructor(personality, age, gender) {
    this.personality = personality;
    this.age = age;
    this.gender = gender;
  }
}

const candidate1 = new Candidate('good', 28, 'woman');

JavaScript์—์„œ๋Š” ํƒ€์ž… ์ •๋ณด๋ฅผ ๋ช…์‹œ์ ์œผ๋กœ ์„ ์–ธํ•˜์ง€ ์•Š๋Š”๋‹ค. ๊ทธ๋ ‡๊ฒŒ ๋•Œ๋ฌธ์— ์œ„์ฒ˜๋Ÿผ๋งŒ ํ‘œ๊ธฐํ•ด๋„ ๋˜์ง€๋งŒ, ํƒ€์ž…์Šคํฌ๋ฆฝํŠธ์—์„œ๋Š” ๊ฐ ์†์„ฑ๊ณผ ๋งค๊ฐœ๋ณ€์ˆ˜์— ํƒ€์ž…์ง€์ •์„ ํ•ด์ฃผ์–ด์•ผ ํ•œ๋‹ค.

// TypeScript
class Candidate {
  personality: string;
  age: number;
  gender: string;

  constructor(personality: string, age: number, gender: string) {
    this.personality = personality;
    this.age = age;
    this.gender = gender;
  }
}

const candidate1 = new Candidate('good', 28, 'woman');

constructor์—๋Š” ๋ณต์ œ๋˜๋Š” ๊ฒƒ์ด ํ•ญ์ƒ object์ด๊ธฐ ๋•Œ๋ฌธ์— return ํƒ€์ž…์„ ์ง€์ •ํ•  ํ•„์š”๋Š” ์—†๋‹ค.


ํƒ€์ž…์Šคํฌ๋ฆฝํŠธ์—์„œ class prototype์— methods ํ•จ์ˆ˜ ๋งŒ๋“ค๊ธฐ

class Candidate {
  personality: string;
  age: number;
  gender: string;

  constructor(personality: string, age: number, gender: string) {
    this.personality = personality;
    this.age = age;
    this.gender = gender;
  }

  selectCadidate(message :string){
    console.log(message)
  }
}

const candidate1 = new Candidate('good', 28, 'woman');
candidate1.selectCadidate('์•ˆ๋…•ํ•˜์„ธ์š”?');

ํŒŒ๋ผ๋ฏธํ„ฐ & return ํƒ€์ž…์ง€์ • ์ž์œ ๋กญ๊ฒŒ ํ•  ์ˆ˜ ์žˆ๋‹ค.


์ถœ์ฒ˜ : ์ฝ”๋”ฉ์• ํ”Œ https://codingapple.com/ / TypeScript Documentation https://www.typescriptlang.org/docs/handbook/2/objects.html