한 걸음씩
[JS][udemy][multicampus] JS Object Literals 본문
1. Object Literals
- objects : collections of properites
- properties : key - value pairs
- Rather than accessing data using an index, we use custom keys
- 키로 구분된 데이터 집합(data collection)을 저장하는 자료형
► property = key + value
- VALID KEYS : all keys are converted to strings
- Except for symbols, which we haven't covered yet
- value : 모든 자료형 가능
- trailing comma : 속성을 추가, 삭제, 이동하기가 용이
const product = {
name : 'Gummy Bears',
inStock : true,
price : 1.99,
flavors : ["grape", "apple", "cherry"]
1999: 'GOOD', // trailing comma
}
// ''따옴표로 묶지 않으면 에러발생
// 대괄호를 써야 먼저 코드를 실행함
product['price']
>> 1.99
// 다음과 같은 방법은 지양할 것
product.price
>> 1.99
// 모든 키는 문자열로 바뀐다!
product['1999']
product[1999]
>> 'GOOD'
► Property 존재 여부 확인
// 'in' 사용
console.log('age' in user)
► 단축 Property
- 키와 값이 같을 경우 단축 구문 사용 가능
const age = 30
const address = 'korea'
const oldUser = {
age: age,
address: address,
}
const newUser = {
age,
address,
}
► 계산된 Property
- 키가 대괄호로 둘러싸여 있는 프로퍼티
- 고정된 값이 아닌 변수 값을 사용할 수 있음
const product = prompt('물건 이름을 입력해주세요')
const prefix = 'my'
const suffix = 'property'
const bag = {
[product]: 5,
[prefix + suffix]: 'value',
}
console.log(bag) // {연필: 5, myproperty: 'value'}
► Adding, Update, Delete property
const midterms = {danielle: 96, thomas: 78}
midterms.thomas = 80
midterms.danielle: A+
midtemrs.winter = 'B+'
midterms['Alice'] = 'D+'
midterms
>> {danielle: 'A+', thomas: 80, winter: 'B+', Alice: 'D+'}
// Delete
delete midterms.thomas
console.log(midterms) // {danielle: 'A+', winter: 'B+', Alice: 'D+'}
2. Nesting arrays and Objects
const comments = [
{username: 'Tammy', text: 'lololo', votes: 9},
{username: 'FishBoi', text: 'glub glub', votes: 12386}
]
// 'glub glub' 접근하기
comments[1]['text']
comments[1].text
>> 'glub glub'
3. Object and Method
► Method
- 객체 속성에 정의된 함수
- 메서드는 객체를 '행동' 할 수 있게 함
const person = {
name: 'Sophia',
greeting: function () {
return 'Hello'
},
}
// greeting 메서드 호출
console.log(person.greeting()) // Hello
▷ 'this' keyword
- python의 self는 선언 시 값이 이미 정해지지만, Js의 this는 함수가 호출되기 전까지 값이 할당되지 않고 호출 시 결정됨(동적)
- 함수나 메서드를 호출한 객체를 가리키는 키워드
- 함수 내에서 객체의 속성 및 메서드에 접근하기 위해 사용
- 'this' 키워드를 사용해 객체에 대한 특정한 작업을 수행할 수 있음
- 'this'는 함수를 호출하는 방법에 따라 가리키는 대상이 다름
- 단순 호출 시 → 전역 객체
- 메서드 호출 시 → 메서드를 호출한 객체
const person = {
name: 'Sophia',
greeting: function () {
return `Hello my name is ${this.name}`
},
}
// greeting 메서드 호출
console.log(person.greeting()) // Hello my name is Sophia
// 단순 호출
const myFunc = function () {
return this
}
console.log(myFunc()) // window
// 브라우저의 최상위 객체인 window를 호출함
// window.document.querySelector 가 있을 때 window는 생략함
// 메서드 호출
const myObj = {
data: 1,
myFunc: function () {
return this
}
}
console.log(myObj.myFunc()) // myObj
// Nested 함수에서의 문제점과 해결책
// forEach의 인자로 들어간 함수는 일반 함수 호출이기 때문에 this가 전역 객체를 가리킴
const myObj2 = {
numbers: [1, 2, 3],
myfunc: function () {
this.numbers.forEach(function (number) {
console.log(number) // 1 2 3
console.log(this) // window
})
}
}
// '화살표 함수'는 자신만의 this를 가지지 않기 때문에 외부 함수에서 this 값을 가져옴
// 메서드 정의 할 때 화살표 함수 사용 금지
const myObj3 = {
numbers: [1, 2, 3],
myfunc: function () {
this.numbers.forEach((number) => {
console.log(number) // 1 2 3
console.log(this) // myObj3
})
}
}
4. JSON
- JavaScript Object Notation
- key-value 형태로 이루어진 자료 표기법
- JS의 Object와 유사한 구조를 가지고 있지만 JSON은 형식이 있는 '문자열'
- JS에서 JSON을 사용하기 위해서는 Object 자료형으로 변경해야 함
const jsObject = {
coffee: 'Americano',
iceCream: 'Cookie and cream',
}
// Object → JSON
const objToJson = JSON.stringify(jsObject)
console.log(objToJson) // {'coffee': 'Americano', 'iceCream': 'Cookie and cream'}
console.log(typeOf objToJson) // string
// JSON → Object
const jsonToObj = JSON.parse(objToJson)
console.log(jsonToObj) // {coffee: 'Americano', iceCream: 'Cookie and cream'}
console.log(typeOf jsonToObj) // object
'JS' 카테고리의 다른 글
[JS][multicampus] Functions (0) | 2023.03.15 |
---|---|
[JS][udemy] Loops (0) | 2023.03.15 |
[JS][multicampus]Basic syntax of JavaScript (0) | 2023.03.14 |
[JS][udemy][multicampus] Arrays (0) | 2023.03.13 |
[JS][udemy] JS 판단 내리기 (0) | 2023.03.13 |