객체

  • 객체 생성
// 객체 생성
var person = {
	// key : value - 프로퍼티
	name : '한아',
	age : 25,
	gender : '여',
	nationality : '대한민국',
	maritalStatus : false
};

 

  • 객체의 프로퍼티 호출 방법
document.write(person.name);
document.write('<br>');
document.write(person['age']);

 

  • 객체의 모든 프로퍼티 출력
// 객체 생성
var product = {
	// 프로퍼티
	name : 'Eclipse',
	price : 99000,
	language : 'Korean',
	supportOS : 'Windows10',
	subscription : true
};

// for in 반복문을 이용한 프로퍼티 출력
for(var key in product){
	document.write(key + ' : ' + product[key] + '<br>');
}

 

  • 객체의 메소드 생성 및 호출
    • this : 객체 내에서 자기 자신이 가지고 있는 프로퍼티를 호출하거나 객체를 참조할 때 사용
// 객체 생성
var person = {
	name:'뽀로로',
	// 메소드 생성
	eat:function(food) {
		// name 호출
		alert(this.name + '가 ' + food + '를 먹어요.');
	}
};

// 메소드 호출
person.eat('쿠키');    // 뽀로로가 쿠키를 먹어요.

 

  • ⚠️ this를 사용하지 않을 때
    • 메소드 내에 선언한 지역변수를 찾고 없을 경우 객체 밖에 선언된 변수를 찾음
var name = '크롱';	// 전역변수

var person = {
	// 프로퍼티
	name:'뽀로로',
	eat:function(food) {
		var name='루피';	// 지역변수
		alert(name + '가 ' + food + '를 먹어요.');
	}
};

person.eat('쿠키');    // 루피가 쿠키를 먹어요.

 

 

프로퍼티, 메소드

  • 객체에 프로퍼티 추가
// 객체 생성
var dog = {};

// 프로퍼티 추가
dog.name = '뽀삐';
dog.age = 5;
dog.breed = '믹스';
dog.weight = 4.5;

 

  • 프로퍼티 존재여부 체크 - in
document.write('age' in dog);    //  true

 

  • 객체에 메소드 추가
dog.play = function(){
	document.write('장난감을 가지고 놀아요.');
};

 

  • 객체의 프로퍼티 제거 - delete
delete dog.weight;	// dog 객체의 weight 프로퍼티 제거

 

 

toString 메소드

  • 객체를 생성하면 자동적으로 Object를 상속받게 되고 Object 안의 메소드를 사용할 수 있음

 

  • toString( ) 메소드
// 객체 생성
var student = {};
document.write(student.toString());  // 출력 : [object Object]
document.write(student);             // toString() 자동 호출

 

  • toString( ) 메소드 재정의
// toString() 재정의
student.toString = function(){
	var attr = '';
	for(var key in this){
		if(key != 'toString'){
			msg += key + ':' + this[key] + '<br>';
		}
	}
	return attr;
};

// 재정의된 toString() 호출
document.write(student.toString());
document.write(student);	// toString() 자동 호출

 

 

배열에 객체 저장

// 배열 생성
var students=[];

// 배열에 객체 추가
students.push({name:'뽀로로', kor:90, eng:90, math:80});
students.push({name:'패티', kor:100, eng:95, math:90});
students.push({name:'크롱', kor:80, eng:90, math:85});
students.push({name:'에디', kor:90, eng:95, math:80});
students.push({name:'루피', kor:95, eng:90, math:100});
students.push({name:'포비', kor:90, eng:100, math:80});

// students 배열 내의 모든 객체에 메소드 추가
for(var i in students) {
	// 총점 계산 메소드
	students[i].getSum = function(){
		return this.kor + this.eng + this.math;
	};

	// 평균 계산 메소드
	students[i].getAvg = function(){
		return this.getSum() / 3;
	};
}

// 출력
var output = '이름 / 총점 / 평균 <br>';
for(var i in students){
	output += students[i].name + ',' + students[i].getSum() + ',' + students[i].getAvg() + '<br>';
}
document.write(output);