본문 바로가기

Web/JavaScript

[JS] 객체

728x90
//Superman
//name: clark
//age: 33

const superman = {
name: 'clark',
age:33,
}

 

객체 접근, 추가, 삭제

접근

superman.name
superman['age']


추가

superman.gender = 'male'
superman['hairColor'] = 'black'


삭제

delete superman.hairColor


단축 프로퍼티

예를 들어

const name = 'clakr';
const age = 33;

const superman = {
name: name,
age: age,
gender: 'male',
}


이런 객체가 있을 시

const superman = {
name,
age,
gender: 'male',
}


로 변경 가능

만약 존재하지 않는 프로퍼티에 접근할 시
undefined발생

이때 in 연산자를 사용하면 프로퍼티가 있는지 확인 가능

'birthDay' in superman;
// false



for...in 반복문 사용시 객체를 순환하며 반복 가능

for(let key in superman) {
console.log(key)
console.log(superman[key])
}



객체 - 메소드

const superman = {
        name: name,
        age: age,
        fly : function() {
        console.log('날아갑니다.')
    }
}



줄여서 사용 시

const superman = {
        name: name,
        age: age,
        fly{
        console.log('날아갑니다.')
    }
}

const user = {
    name: 'Mike',
    sayHello: function() {
        console.log(`Hello, I'm ${this.name}`);
    }
}


이런식으로 작성 시 user의 name을 가르키게 됨

let boy = {
    name: 'Mike',
    sayHello: () => {
        console.log(this);
    }
}


이런식으로 화살표 함수로 작성 시 this는 boy를 가르키지 않음
this는 전역객체를 가르키게 됨
브라우저 환경에서는 window, Node.js 환경에서는 global이 전역객체가 됨

728x90

'Web > JavaScript' 카테고리의 다른 글

[JS] 변수 심화  (1) 2024.02.06
[JS] 배열  (0) 2024.02.05
[JS] 함수2  (2) 2024.02.05
[JS] 함수  (1) 2024.01.30
[JS] 반복문, Switch  (0) 2024.01.30