You don't know JS - object (1)

winters0727Β·2021λ…„ 10μ›” 4일
0

You don't know JS

λͺ©λ‘ 보기
4/4
post-thumbnail

객체 생성 πŸ˜€

객체 생성 ꡬ문은 선언적(λ¦¬ν„°λŸ΄) ν˜•μ‹κ³Ό μƒμ„±μž ν˜•μ‹μœΌλ‘œ μ •μ˜λœλ‹€.

// λ¦¬ν„°λŸ΄ ν˜•μ‹
const myObjt1 = {
  a : 2
}

// μƒμ„±μž ν˜•μ‹
const myObj2 = new Object()
myObjt2.a = 2

각각의 ν˜•μ‹μœΌλ‘œ μƒμ„±λœ κ°μ²΄λŠ” μ„œλ‘œ λ™μΌν•œ ν˜•νƒœλ₯Ό 가진닀. λ‹€λ§Œ, λ¦¬ν„°λŸ΄ ν˜•μ‹μ€ ν•œ 개의 ꡬ문으둜 λ‹€μˆ˜μ˜ ν‚€-κ°’ μŒμ„ ν”„λ‘œνΌν‹°λ‘œ μΆ”κ°€ν•  수 μžˆμ§€λ§Œ, μƒμ„±μž ν˜•μ‹μ€ ν•œ 개의 ꡬ문에 ν•˜λ‚˜μ˜ ν‚€-κ°’ μŒμ„ ν”„λ‘œνΌν‹°λ‘œ μΆ”κ°€ν•  수 μžˆλ‹€.

νƒ€μž… 😁

μžλ°”μŠ€ν¬λ¦½νŠΈ λͺ…μ„Έμ—μ„œ μ„€λͺ…ν•˜λŠ” 객체의 νƒ€μž…μ€ λ‹€μŒκ³Ό κ°™λ‹€.

  • null
  • undefined
  • boolean
  • number
  • string
  • object
  • symbol(ES6μ—μ„œ μΆ”κ°€)

μœ„μ˜ 7개의 νƒ€μž…μ„ 'λ‹¨μˆœ μ›μ‹œ νƒ€μž…'이라고 ν•œλ‹€.
κ·Έ 외에 λ‹¨μˆœ μ›μ‹œ νƒ€μž…κ³Ό κ΅¬λΆ„λ˜λŠ” '볡합 μ›μ‹œ νƒ€μž…'μ΄λΌλŠ” λ…νŠΉν•œ 객체 ν•˜μœ„ νƒ€μž…μ΄ μžˆλ‹€.(function, array...)

λ‚΄μž₯ 객체
λ‚΄μž₯ κ°μ²΄λŠ” 객체의 ν•˜μœ„ νƒ€μž…μ΄λ‹€.

  • String
  • Number
  • Boolean
  • Object
  • Function
  • Array
  • Date
  • RegExp
  • Error

λ‚΄μž₯ κ°μ²΄λŠ” νƒ€μž… λ˜λŠ” λ‹€λ₯Έ μ–Έμ–΄μ—μ„œ μ •μ˜ν•œ 클래슀처럼 착각할 수 μžˆμ§€λ§Œ, μ‹€μ œλ‘œ λ‚΄μž₯ κ°μ²΄λŠ” μžλ°”μŠ€ν¬λ¦½νŠΈμ˜ λ‚΄μž₯ ν•¨μˆ˜λ‘œ new μƒμ„±μž μ˜ˆμ•½μ–΄μ™€ ν•¨κ»˜ μ‚¬μš©λ˜μ–΄ 주어진 ν•˜μœ„ νƒ€μž…μ˜ 객체λ₯Ό μƒμ„±ν•˜λŠ”λ° μ‚¬μš©λœλ‹€.
λ¦¬ν„°λŸ΄ ν˜•μ‹μœΌλ‘œ μ •μ˜λœ strLiteralκ³Ό μƒμ„±μž ν˜•μ‹μœΌλ‘œ μ •μ˜λœ strObjectλ₯Ό λΉ„κ΅ν•˜λ©΄ λ‹€μŒκ³Ό κ°™λ‹€.

const strLiteral = 'string'
const strObject = new String('string')

typeof strLiteral // string
typeof strObject // object

strLiteral instanceof String // false
strObject instanceof String // true

strLiteral == strObject // true
strLiteral === strObject // false

toString.call(strLiteral) // [object String]
toString.call(strObject) // [object String]

strLiteral, strObjectλŠ” 생성 ꡬ문 ν˜•μ‹λ§Œ λ‹€λ₯Ό 뿐, λ™μΌν•œ λ¬Έμžμ—΄μ„ κ°€μ§€κ²Œ 생성됐닀. ν•˜μ§€λ§Œ, 두 λ³€μˆ˜κ°€ 차이λ₯Ό λ³΄μ΄λŠ” κ²ƒμœΌλ‘œ 보아 λ¦¬ν„°λŸ΄ ν˜•μ‹κ³Ό μƒμ„±μž ν˜•μ‹μœΌλ‘œ μƒμ„±λœ λ¬Έμžμ—΄μ€ λ‹€λ₯Έ κ°’μœΌλ‘œ 보인닀.

const strLiteral = 'string'
const strObject = new String('string')

const strLiteral2 = 'string'
const strObject2 = new String('string')

strLiteral == strLiteral2 // true
strLiteral === strLiteral2 // true

strObject == strObject2 // false
strObject === strObject2 // false

λ¦¬ν„°λŸ΄ ν˜•μ‹μœΌλ‘œ μƒμ„±λœ 두 λ³€μˆ˜λŠ” λ™μΌν•œ 반면, μƒμ„±μž ν˜•μ‹μœΌλ‘œ μƒμ„±λœ 두 λ³€μˆ˜λŠ” λ‹€λ₯΄λ‹€. μ΄λŸ¬ν•œ 차이점은 μ–΄λ””μ—μ„œ μ˜€λŠ” κ²ƒμΌκΉŒ? πŸ€”

You don't know JS - object (2)둜 μ΄μ–΄μ§‘λ‹ˆλ‹€.

profile
ν•¨κ»˜ μ„±μž₯ν•˜λŠ” 개발자

0개의 λŒ“κΈ€