자바스크립트 참조 타입
자바스크립트에서 숫자, 문자열, 불린값, null, undefined 같은 기본 타입을 제외한 모든 값을 객체입니다.따라서 배열, 함수, 정규표현식 등 모두 객체로 표현됩니다.

참조타입인 객체는 하나의 값만 가지는 것이 아닌 여러 개의 프로퍼티들을 포함할 수 있습니다.
또한, 객체의 프로퍼티는 함수로 포함할 수 있으며, 자바스크립트에서는 프로터피를 메서드라고 부릅니다.
객체를 생성하는 방법 3가지는 예시로 보여드리겠습니다.
1. Object()를 이용한 객체 생성
var newObj = new Object();
newObj.color = 'red';
newObj.backgroundColor = 'blue';
console.log(newObj) // { color: 'red', backgroundColor: 'blue' } 와 같이 출력 됩니다.
2. 객체 리터럴 방식으로 객체 생성
var newObj = {
color: 'red',
backgroundColor: 'blue'
};
console.log(newObj) // { color: 'red', backgroundColor: 'blue' } 출력
3. 생성자 함수로 객체 생성
function newFuc(a, b){
return a+b;
}
newFuc.result = newFuc(5,3);
newFuc.status = 'FAIL';
console.log(newFuc.result); // 8 (출력)
console.log(newFuc.status); // 'FAIL' (출력)
자바스크립트에서는 이와 같이 객체 생성을 할 수 있으며, 함수도 객체인 것을 알 수 있습니다.
객체를 생성하는 함수는 생성자 함수라고 부릅니다.
객체를 생성했으면 객체를 읽고, 쓰고, 갱신하는 방법을 알아봐야합니다.
객체 읽는 방법 ( 두 가지 사용법 )
var newObj = {
color: 'red',
backgroundColor: 'blue'
};
마침표(.) 표기법
console.log(newObj.color) // 'red' (출력)
대괄호([]) 표기법
console.log(newObj['backgroundColor']) // 'blue' (출력)
객체안에 있는 값을 순서대로 출력하는 방법
var newObj = {
color: 'red',
backgroundColor: 'blue',
fontSize: '15px'
};
// 빈 변수 선언
var prop;
// for in 문을 통한 객체 값 출력
for (prop in newObj) {
console.log(prop, newObj[prop]);
}
// 출력
// color 'red'
// background 'blue'
// fontSize '15px'
객체 프로터피 삭제하는 방법
var newObj = {
color: 'red',
backgroundColor: 'blue'
};
console.log(newObj.color) // 'red' 출력
delete newObj.color;
console.log(newObj.color) // undefined 출력
이와 같이 참조 타입인 객체 다루는 방법을 알아봤습니다.
'javascript' 카테고리의 다른 글
| [javascript] 자바스크립트 프로토타입 (0) | 2020.05.22 |
|---|---|
| [javascript] 참조 타입의 특성 - 객체 값 참조 (0) | 2020.05.21 |
| [javascript] 자바스크립트 기본 타입 ( 숫자, 문자열, 불린값, null, undefined) (0) | 2020.05.19 |
| [javascript] substring(),indexOf() 문자열 추출과 문자열 찾기 (0) | 2020.05.18 |
| [javascript] 자바스크립트 for 문, for in 문, forEach 문 - 반복문 편 (0) | 2020.05.16 |