728x90
반응형
객체에는 key와 value로 구성된 프로퍼티가 들어간다. 프로퍼티는 쉼표로 구분한다.
마지막 쉼표는 없어도 되지만 있는 것이 수정, 삭제, 이동할 때 용이하다.
const superman = {
name : 'clark',
age : 33,
}
접근
superman.name // 'clark'
superman['age'] // 33
추가
superman.gender = 'male';
superman['hairColor'] = 'black';
삭제
delete superman.hairColor;
단축 프로퍼티
const name = 'clark';
const age = 33;
const superman = {
name : name,
age : age,
gender : 'male',
}
객체의 name에는 name 변수가, age에는 age 변수가 들어가 있다.
이 코드는 다음과 같이 쓸 수 있다.
const name = 'clark';
const age = 33;
const superman = {
name,
age,
gender : 'male',
}
프로퍼티 존재 여부 확인
존재하지 않는 프로퍼티에 접근한다면 에러가 나지 않고 undefined가 나온다.
superman.birthDay; // undefined
이 때 in 연산자를 사용하면 프로퍼티가 있는지 확인할 수 있다.
'birthDay' in superman; // false
'age' in superman; // true
for..in 반복문
for(let key in superman){
console.log(key)
console.log(superman[key])
}
method
: 객체 프로퍼티로 할당된 함수
const superman = {
name : 'clark';
age : 33,
fly : function(){
console.log('날아갑니다.')
}
}
superman.fly(); //날아갑니다.
단축 코드로도 작성할 수 있다.
const superman = {
name : 'clark';
age : 33,
fly(){
console.log('날아갑니다.')
}
}
this
객체와 메서드의 관계에 대해 알아보자.
const user = {
name : 'Mike',
sayHello : function(){
console.log(`Hello, I'm ${user.name}`);
}
}
위와 같은 방식은 문제가 발생할 수 있다. 이럴 때는 this라는 키워드를 쓰면 된다.
const user = {
name : 'Mike',
sayHello : function(){
console.log(`Hello, I'm ${this.name}`);
}
}
user.sayHello(); // Hello, I'm Mike
user.sayHello()에서 user는 this가 된다.
다른 예시를 만들어보면
let boy = {
name : 'Mike',
sayHello,
}
let girl = {
name : 'Jane',
sayHello,
}
sayHello : function(){
console.log(`Hello, I'm ${this.name}`);
}
boy.sayHello(); // I'm Mike
girl.sayHello(); // I'm Jane
this는 런타임에 결정된다.
** 주의할 점
화살표 함수는 일반 함수와는 달리 자신만의 this를 가지지 않는다. 화살표 함수 내부에서 this를 사용하면, 그 this는 외부에서 값을 가져온다.
let boy = {
name : 'Mike',
sayHello : () => {
console.log(this);
}
}
boy.sayHello();
this는 boy 객체를 가리키지 않고 전역 객체를 가리킨다.
브라우저 환경에서 전역 객체는 window이고, Node js 환경에서 전역 객체는 global이다.
728x90
반응형
'Language > Javascript' 카테고리의 다른 글
[Javascript] 심볼(Symbol) (0) | 2021.12.17 |
---|---|
[Javascript] 계산된 프로퍼티(Computed property), 객체 메소드(Object methods) (0) | 2021.11.16 |
[Javascript] 생성자 함수 (0) | 2021.11.15 |
[Javascript] 함수 표현식, 화살표 함수(arrow function) (0) | 2021.11.15 |
[Javascript] var, let, const의 차이 - 호이스팅, TDZ, scope (0) | 2021.11.15 |