ES6 Classes
Class๋ ๊ฐ์ฒด๋ฅผ ์์ฑํ๊ธฐ ์ํ ํ ํ๋ฆฟ์ด๋ค.
ํด๋์ค๋ ๋ฐ์ดํฐ์ ์ด๋ฅผ ์กฐ์ํ๋ ์ฝ๋๋ฅผ ํ๋๋ก ์ถ์ํํ๋๋ฐ ์๋ฐ์คํฌ๋ฆฝํธ์์ ํด๋์ค๋ ํ๋กํ ํ์ ์ ์ด์ฉํด์ ๋ง๋ค์ด์ก์ง๋ง ES5์ ํด๋์ค ์๋ฏธ์๋ ๋ค๋ฅธ ๋ฌธ๋ฒ๊ณผ ์๋ฏธ๋ฅผ ๊ฐ์ง๋ค.
const imae = {
name: 'imae',
normal: function () {
console.log(this.name)
},
arrow: () => {
console.log(this.name)
}
}
imae.normal()
imae.arrow()
์คํ ๊ฒฐ๊ณผ
imae
undefined
ES6์์๋ ํด๋์ค ๋ฌธ๋ฒ์ ํ๋ด๋ด๋ ๊ฒ์ด ๊ฐ๋ฅํ๋ค.
prototype์ ์ฐ๋ ๋์ class๋ฅผ ์ฌ์ฉํ์ฌ ์์ฑ์ ํจ์๋ฅผ ๋ง๋ค ์ ์๋ค.
function User(first, last) {
this.firstName = first
this.lastName = last
}
User.prototype.getFullName = function () {
return `${this.firstName} ${this.lastName}`
}
๋ฐฉ๋ฒ1์ด๋ผ๊ณ ํ์, ์ด ๋ฐฉ๋ฒ์ ES6์ classes๋ฅผ ์ฌ์ฉํ๋ฉด ๋์ฑ๋ ์ฝ๋๊ฐ ๊ฐํธํด์ง๋ค.
class User {
constructor(first, last) {
this.firstName = first
this.lastName = last
}
getFullName() {
return `${this.firstName} ${this.lastName}`
}
}
์ด๋ฌํ ๋ฐฉ๋ฒ์ ์ฌ์ฉํ์ฌ ์ถ๋ ฅํ๋ฉด ๋์ผํ ๊ฒฐ๊ณผ๊ฐ ๋์จ๋ค.
constructor (์์ฑ์)
constructor ๋ฉ์๋๋ class๋ก ์์ฑ๋ ๊ฐ์ฒด๋ฅผ ์์ฑํ๊ณ ์ด๊ธฐํํ๊ธฐ ์ํ ํน์ํ ๋ฉ์๋์ด๋ค.
"constructor" ๋ผ๋ ์ด๋ฆ์ ๊ฐ์ง ํน์ํ ๋ฉ์๋๋ ํด๋์ค ์์ ํ ๊ฐ๋ง ์กด์ฌํ ์ ์๋ค.
๋ง์ฝ ํด๋์ค์ ์ฌ๋ฌ ๊ฐ์ constructor ๋ฉ์๋๊ฐ ์กด์ฌํ๋ฉด SyntaxError๊ฐ ๋ฐ์ํ๋ค.
'๐ค Language > ๐จ JavaScript' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
JS. ๋ฌธ์ (0) | 2022.02.20 |
---|---|
JS. ์์(ํ์ฅ) (0) | 2022.02.15 |
JS. this (0) | 2022.02.15 |
JS. ์์ฑ์ ํจ์(prototype) (0) | 2022.02.15 |
JS. ์ฝ๋ฐฑ(CallBack) (0) | 2022.02.13 |