๋ณธ๋ฌธ ๋ฐ”๋กœ๊ฐ€๊ธฐ
  • What would life be If we had no courage to attemp anything?
Language/JavaScript

JavaScript - ํ”„๋กœํ† ํƒ€์ž…(prototype), ํด๋ž˜์Šค(class)

by DevIseo 2022. 5. 3.

๐Ÿคํ”„๋กœํ† ํƒ€์ž…(prototype)

|JS์˜ ์ƒ์†๊ณผ ๊ฐ์ฒด

  • JS๋Š” ๊ฐ์ฒด์ง€ํ–ฅ ํ”„๋กœ๊ทธ๋ž˜๋ฐ ์–ธ์–ด
  • JS์˜ ๊ฐ์ฒด๋Š” key-value ๊ตฌ์กฐ์˜ ์ž๋ฃŒ๊ตฌ์กฐ
  • Python๊ณผ ๊ฐ™์€ ํด๋ž˜์Šค๊ธฐ๋ฐ˜์˜ ๊ฐ์ฒด์ง€ํ–ฅ ํ”„๋กœ๊ทธ๋ž˜๋ฐ ์–ธ์–ด์˜ ๊ฐ์ฒด์™€ ๋‹ค๋ฆ„
  • JS๋Š” ํด๋ž˜์Šค๊ฐœ๋…์ด ์กด์žฌํ•˜์ง€ ์•Š๊ณ , ํ”„๋กœํ† ํƒ€์ž…์ด๋ผ๋Š” ๊ฐœ๋…์„ ํ™œ์šฉํ•ด ์ƒ์†์„ ๊ตฌํ˜„
  • ES5 ๊นŒ์ง€๋Š” ์ด๋Ÿฌํ•œ ๋ฐฉ์‹์œผ๋กœ ์›ํ•˜๋Š” ๊ฐ์ฒด๋ฅผ ์ƒ์„ฑํ•˜์˜€์œผ๋‚˜, ES6+ ๋ถ€ํ„ฐ๋Š” class ํ‚ค์›Œ๋“œ๋กœ ๋Œ€์ฒด
function Rectangle(width, height) {
 this.width = width
 this.height = height
}
Rectangle.prototype.getArea = function () {
 return this.width * this.height
}
function Square(length) {
 Rectangle.call(this, length, length)
 this.isSquare = true
}
Square.prototype = Object.create(Rectangle.prototype)
Square.prototype.constructor = Square
Square.prototype.getPerimeter = function () {
 return 2 * (this.width + this.height)
}
const s1 = new Square(2)

 

|์ƒ์„ฑ์ž ํ•จ์ˆ˜

์ƒ์„ฑ์ž ํ•จ์ˆ˜์™€ prototype,constructor์˜ ๊ด€๊ณ„
์ƒ์„ฑ์ž ํ•จ์ˆ˜์™€ prototype, constructor

 

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

|ES6์—์„œ ์ถ”๊ฐ€๋œ class ํ‚ค์›Œ๋“œ

  • ํด๋ž˜์Šค๋ฅผ ์‚ฌ์šฉํ•˜๋Š” ๊ฐ์ฒด์ง€ํ–ฅ ํ”„๋กœ๊ทธ๋ž˜๋ฐ ์–ธ์–ด์ฒ˜๋Ÿผ ๊ฐ์ฒด๋ฅผ ์ƒ์„ฑํ•  ์ˆ˜ ์žˆ๋„๋ก class ํ‚ค์›Œ๋“œ ๋“ฑ์žฅ
  • ์ƒ์† ์—ญ์‹œ ํ›จ์”ฌ ์ง๊ด€์ ์œผ๋กœ ๊ตฌ์„ฑ
  • ์‹ค์ œ๋กœ ํด๋ž˜์Šค-์ธ์Šคํ„ด์Šค์˜ ๊ตฌ์กฐ๋กœ ๋ฐ”๋€ ๊ฒƒ์ด ์•„๋‹˜. ์—ฌ์ „ํžˆ ๋‚ด๋ถ€์ ์œผ๋กœ๋Š” ํ”„๋กœํ† ํƒ€์ž…์„ ์‚ฌ์šฉ
class Rectangle {
 constructor(width, height) {
 this.width = width
 this.height = height
 } 
 
 getArea() {
 return this.width * this.height
 }
}
class Square extends Rectangle {
 constructor(length) {
 super(length, length)
 this.isSquare = true
 }
 getPerimeter() {
 return 2 * (this.width + this.height)
 }
}
const s1 = new Square(2)

|JS ํด๋ž˜์Šค์˜ ๊ตฌ์„ฑ ์š”์†Œ

  • class ํ‚ค์›Œ๋“œ ๋’ค์— ์‹๋ณ„์ž ์ด๋ฆ„ ์ง€์ • .(Upper Camel Case ์‚ฌ์šฉ)
  • ๋‹ค๋ฅธ ํด๋ž˜์Šค๋ฅผ ์ƒ์†ํ•  ๊ฒฝ์šฐ ์‹๋ณ„์ž ์ด๋ฆ„ ๋’ค์— extends ํ‚ค์›Œ๋“œ๋ฅผ ๋ถ™์ด๊ณ , ์ƒ์†๋ฐ›๊ณ ์ž ํ•˜๋Š” ํด๋ž˜์Šค์ด๋ฆ„ ๊ธฐ์ž….
  • ์ค‘๊ด„ํ˜ธ๋กœ ๋ธ”๋ก์„ ์ƒ์„ฑํ•˜๊ณ , ๋‚ด๋ถ€ ๋ฉ”์„œ๋“œ ์ •์˜๋Š” function ํ‚ค์›Œ๋“œ ์—†์ด ์ •์˜.
  • ์ƒ์„ฑ์ž ํ•จ์ˆ˜๋Š” constructor๋ผ๋Š” ์ด๋ฆ„์œผ๋กœ ์ •์˜. (Python ์˜ init ๊ณผ ๊ฐ™์Œ)
  • this๋กœ ๊ฐ์ฒด์˜ ์†์„ฑ ์ •์˜. (Python์˜ self์™€ ๊ฐ™์Œ)
  • ํ•˜์œ„ํด๋ž˜์Šค์—์„œ ์ƒ์„ฑ์ž ํ•จ์ˆ˜๋ฅผ ์ •์˜ํ•  ๊ฒฝ์šฐ, super()๋ฅผ ํ†ตํ•ด ์ƒ์œ„ํด๋ž˜์Šค์˜ ์ƒ์„ฑ์ž ํ•จ์ˆ˜๋ฅผ ํ˜ธ์ถœํ•ด์•ผ ํ•จ

๋Œ“๊ธ€