- 변경 가능한 속성들의 집합
- 이름과 값이 있는 속성들을 포함하는 컨테이너
- 데이터를 모으고 구조화 하는데 이용
1) 객체의 생성
- 중괄호({ })를 이용하여 생성
- 중괄호({ })안에 아무것도 적지 않으면 빈 객체 생성
- 중괄호({ })안에 속성값 표현 {'속성이름':'속성값', ...}
2) 객체의 속성값 읽기
- 대괄호([ ]) 표기법
객체 뒤의 대괄호 안에 속성 이름을 문자열로 적어 속성에 접근
- 마침표(.) 표기법 // 많이 사용
객체 뒤에 마침표를 찍고, 속성 이름을 적어 속성에 접근
3) 속성과 메서드
- <script>
- var clothes = {
- name:'suit',
- top:100,
- bottom:32,
- color:'black'
- };
- console.log(clothes['name']); // suit
- console.log(clothes['top']); // 100
- console.log(clothes.bottom); // 32
- console.log(clothes.color); // black
- </script>
① 속성
모든 형태의 자료형을 가질 수 있다
(숫자, 문자열, 불린, null, undefined, 배열, 함수, 객체 등)
② 메서드
속성값이 함수인 속성으로 객체의 속성이름 뒤에 괄호를 열고닫아 접근한다
- <script>
- var clothes = {
- name:'suit',
- top:100,
- bottom:32,
- color:'black',
- print:function(){
- var out='';
- out+='name:'+this.name+'\n';
- out+='top:'+this.top+'\n';
- out+='bottom:'+this.bottom+'\n';
- out+='color:'+this.color;
- console.log(out);
- }
- };
- clothes.print();
- </script>
4) 관련 키워드
① for in
② in*속성에 접근할 순 없다
- <script>
- var clothes = {
- name:'suit',
- top:100,
- bottom:32,
- color:'black',
- print:function(){
- var out='';
- out+='name:'+this.name+'\n';
- out+='top:'+this.top+'\n';
- out+='bottom:'+this.bottom+'\n';
- out+='color:'+this.color;
- console.log(out);
- }
- };
- var forin = '';
- for(var attr in clothes) {
- forin += attr + ' ';
- }
- console.log(forin); // name top bottom color print
- </script>
객체에 속성이 존재하는지 확인 할 수 있다. (존재 true, 미존재 false 반환)
③ with
- <script>
- var clothes = {
- name:'suit',
- top:100,
- bottom:32,
- color:'black',
- print:function(){
- var out='';
- out+='name:'+this.name+'\n';
- out+='top:'+this.top+'\n';
- out+='bottom:'+this.bottom+'\n';
- out+='color:'+this.color;
- console.log(out);
- }
- };
- console.log('name' in clothes); // true
- </script>
반복할 객체를 생략하고 속성과 메서드를 사용할 수 있으나, 실행 속도 저하
5) 속성의 수정
① 속성에 추가 및 변경
대괄호 표기법 또는 마침표 표기법을 이용하여 값을 할당하여 추가 및 변경
가능하다. 속성이 존재할 경우 속성값이 수정되며, 미존재할 경우 추가된다.
② 속성의 제거
delete 키워드를 이용하여 제거한다.
- <script>
- var clothes = {
- name:'suit',
- top:100,
- bottom:32,
- color:'black',
- print:function(){
- var out='';
- out+='name:'+this.name+'\n';
- out+='top:'+this.top+'\n';
- out+='bottom:'+this.bottom+'\n';
- out+='color:'+this.color;
- console.log(out);
- }
- };
- delete clothes.top;
- delete (clothes.bottom);
- for(var attr in clothes) {
- console.log(attr); // name, color (top, bottom 제외)
- }
- </script>
댓글 없음:
댓글 쓰기