본문 바로가기

javascript

[javascript] 자바스크립트 참조 타입 (객체 타입)

자바스크립트 참조 타입

 

자바스크립트에서 숫자, 문자열, 불린값, 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 출력

 

 

이와 같이 참조 타입인 객체 다루는 방법을 알아봤습니다.