๐คํ๋กํ ํ์ (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)
|์์ฑ์ ํจ์
๐คํด๋์ค(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()๋ฅผ ํตํด ์์ํด๋์ค์ ์์ฑ์ ํจ์๋ฅผ ํธ์ถํด์ผ ํจ
'Language > JavaScript' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
JavaScript - Asynchronous JavaScript(์ฝ๋ฐฑํจ์, Async callbacks,Promise), Axios (0) | 2022.05.03 |
---|---|
JavaScript - AJAX, Asynchronous (๋น๋๊ธฐ) (0) | 2022.05.03 |
JavaScript - this (0) | 2022.05.02 |
JavaScript - ๊ฐ์ฒด(Objects) (0) | 2022.04.27 |
JavaScript - ๋ฐฐ์ด(Arrays) (0) | 2022.04.27 |
๋๊ธ