[JavaScript] Object_01

최은서·2023년 11월 7일

1. declaration

<title>객체</title>
</head>
<body>
<script type="text/javascript">

	//객체 정의
	const product = {
		//속성(key(프로퍼티):value)
		제품명:'휴대폰',
		제품번호:'A1001',
		기능:'멀티윈도우',
		원산지:'대한민국',
		가격:1000,
		업데이트지원:true, //마지막 쉼표는 무시됨
	};
	
	//객체의 속성 호출
	//				객체명.key
	document.write(product.제품명 + '<br>');
	document.write(product.원산지 + '<br>')
	//				객체명[key]
	document.write(product['가격'] + '<br>');
	document.write(product['업데이트지원']);
</script>
</body>
</html>

2. loop

<title>반복문을 이용해서 객체의 속성 읽기</title>
</head>
<body>
<script type="text/javascript">

	//객체 정의
	const product = {
		//속성(key:value)
		name:'eclipse',
		price:'10,000',
		language:'한국어',
		supportOS:'win10',
		subscription:true,
	};
	
	//반복문을 이용한 속성 읽기
	for(let key in product){
		//for in 반복문을 이용해서 속성에 접근할 때는 객체로부터 key를 문자열로 반환받기 때문에
		//객체명[문자열 key] 형식으로 호출해서 속성에 접근할 수 있음
								//product.key는 안됨(내부에 있는 key라는 문자열로 인식)
		document.write(key + ':' + product[key] + '<br>');
	}

</script>
</body>
</html>

3. method

<title>객체의 속성과 메서드 사용</title>
</head>
<body>
<script type="text/javascript">

	let name = '유재석'; //전역변수
	
	//객체 정의
	const person = {
		//속성 지정
		name:'홍길동',
		//메서드 지정
		eat:function(food){
			let name = '강호동'; //지역변수
			//객체 내부에서 객체의 속성 및 메서드를 호출할 때는 this를 명시해야 호출 가능함
			//this는 객체 자신을 의미함
			document.write(this.name + '이 ' + food + '을 먹습니다.<br>');
			//this를 명시하지 않고 식별자를 명시하면 전역변수 또는 지역변수로 인식(지역변수가 전역변수보다 우선임)
			document.write(name + '이 ' + food + '을 먹습니다.');
		}
	};
	//메서드 호출
	person.eat('밥');

</script>
</body>
</html>
[실행결과]
홍길동이 밥을 먹습니다.
강호동이 밥을 먹습니다.

4. insert

<title>빈 객체에 속성 추가</title>
</head>
<body>
<script type="text/javascript">

	const student ={};
	
	//객체에 속성 추가
	student.이름 = '홍길동';
	student.취미 = '악기';
	student.특기 = '프로그래밍';
	student.장래희망 = '프로그래머';
	
	//in 키워드를 이용해서 객체 내의 속성 존재 여부 체크
	document.write('특기' in student);
	document.write('<br>');
	document.write(student.특기 + '<br>');
	document.write('-------------<br>');
	
	//객체에 메서드 추가
	student.play = function(){
		document.write('피아노를 연주하다');
	};
	
	//반복문을 이용해서 속성과 메서드 출력
	for(let key in student){
		document.write(key + ' : ' + student[key] + '<br>');
	}

</script>
</body>
</html>
[실행결과]
true
프로그래밍
-------------
이름 : 홍길동
취미 : 악기
특기 : 프로그래밍
장래희망 : 프로그래머
play : function(){ document.write('피아노를 연주하다'); }

5. toString

<title>toString() 메서드 사용</title>
</head>
<body>
<script type="text/javascript">

	const student = {};
	
	document.write(student + '<br>');
	document.write(student.toString() + '<br>');
	document.write('--------------------<br>');
	
	//객체에 속성 추가
	student.이름 = '홍길동';
	student.취미 = '악기';
	student.특기 = '프로그래밍';
	student.장래희망 = '프로그래머';
	
	for(let key in student){
		document.write(key + ' : ' + student[key] + '<br>');
	}
	document.write('--------------------<br>');
	
	//객체에 메서드 추가
	student.toString = function(){
		let msg = '';
		for(let key in this){ //this : 객체 안에서 객체 참조
			if(key != 'toString'){ //toString 메서드 제외
			msg += key + ' : ' + this[key] + '<br>';
			}
		}
		return msg;
	};
	
	document.write(student.toString() + '<br>');
	document.write('--------------------<br>');
	document.write(student); //재정의된 toString으로 동작
	
</script>
</body>
</html>

6. delete

<title>속성 제거</title>
</head>
<body>
<script type="text/javascript">

	//객체 정의
	const product = {};
	
	//객체에 속성 추가
	product.이름 = '건조기';
	product.가격 = 20000;
	product.색상 = '흰색';
	product.제조사 = 'LG';
	
	//toString() 메서드 추가
	product.toString = function(){
		let output = '';
		for(let key in this){
			if(key != 'toString'){
				output += key + ' : ' + this[key] + '<br>';
			}
		}
		return output;
	};
	
	document.write(product);
	document.write('-----------------<br>');
	
	//속성을 제거
	delete product.제조사;
	document.write(product);
	
	
</script>
</body>
</html>

0개의 댓글