[JavaScript] Object_02

최은서·2023년 11월 8일

7. array

<title>배열에 객체 저장</title>
</head>
<body>
<script type="text/javascript">

	//빈 배열 정의
	const students = [];
	
	//객체를 배열에 저장
	students.push({이름:'홍길동',국어:99,영어:98,수학:97,과학:96});
	students.push({이름:'박문수',국어:98,영어:93,수학:94,과학:91});
	students.push({이름:'장영실',국어:97,영어:98,수학:95,과학:96});
	students.push({이름:'김유신',국어:89,영어:94,수학:97,과학:92});
	students.push({이름:'이순신',국어:92,영어:98,수학:97,과학:96});
	 
	//students 배열내의 모든 객체에 메서드 추가
	for(let i in students){
		//총점 구하는 메서드 추가
		students[i].getSum = function(){
			return this.국어 + this.영어 + this.수학 + this.과학;
		};
		//평균 구하는 메서드 추가
		students[i].getAverage = function(){
			return this.getSum() / 4;
		};
	}
	
	document.write('이름, 총점, 평균<br>');
	document.write('--------------------<br>');
	
	for(let i in students){
		document.write(students[i].이름 + ', ' + students[i].getSum()
				+ ', ' + students[i].getAverage() + '<br>');
	}
	
</script>
</body>
</html>

8. function

<title>생성자 함수</title>
</head>
<body>
<script type="text/javascript">
	//생성자 함수 정의
	function Animal(name,age){
		//속성
		this.name = name;
		this.age = age;
		//메서드
		this.eat = function(){
			document.write('맛있는 먹이를 먹습니다.');
		};
	}
	
	//생성자 함수를 이용해서 객체 생성
	const animal = new Animal('비둘기',10);
	
	//속성 호출
	document.write(animal.name + '<br>');
	document.write(animal.age + '<br>');
	
	//메서드 호출
	animal.eat();

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

9. constructor

<title>생성자 함수</title>
</head>
<body>
<script type="text/javascript">

	//생성자 함수 지정
	function Student(name,korean,math,english,science){
		//속성 지정
		this.이름 = name;
		this.국어 = korean;
		this.수학 = math;
		this.영어 = english;
		this.과학 = science;
		//메서드 지정
		this.getSum = function(){ //총점 구하기
			return this.국어 + this.수학 + this.영어 + this.과학;
		};
		this.getAverage = function(){ //평균 구하기
			return this.getSum() / 4;
		};
		this.toString = function(){
			return this.이름 + ', ' + this.getSum() + ', ' + this.getAverage();
		};
	}
	
	//객체 생성
	const student = new Student('홍길동',99,93,98,97);
	document.write(student);
	document.write('<br>--------------------<br>');
	
	//배열과 객체를 활용해서 여러명의 성적 데이터 처리하기
	
	//빈 배열
	const students = [];
	students.push(new Student('박문수',99,98,91,88));
	students.push(new Student('장영실',97,98,93,87));
	students.push(new Student('김유신',96,98,92,84));
	students.push(new Student('이순신',95,98,90,83));
	students.push(new Student('강호동',94,98,91,81));
	//--> 객체를 각각 생성하면 매번 메서드도 새로 생성됨, 짧게 줄일 수 있게하기
	
	//출력
	document.write('이름, 총점, 평균<br>');
	
	for(let i in students){
		document.write(students[i].toString() + '<br>');
	}

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

10. prototype

<title>프로토타입을 사용한 메서드 정의</title>
</head>
<body>
<script type="text/javascript">

	//생성자 함수 정의
	function Student(name,korean,math,english,science){
		//속성 지정
		this.이름 = name;
		this.국어 = korean;
		this.수학 = math;
		this.영어 = english;
		this.과학 = science;
	}
	//프로토타입은 생성자 함수를 사용해 생성된 객체가 공통으로 가지는 공간
	Student.prototype.getSum = function(){
		return this.국어 + this.수학 + this.영어 + this.과학;
	};
	Student.prototype.getAverage = function(){
		return this.getSum() / 4;
	};
	Student.prototype.toString = function(){
		return this.이름 + ', ' + this.getSum() + ', ' + this.getAverage();
	}
	
	//빈 배열 생성
	const students = [];
	
	students.push(new Student('홍길동',99,98,97,96));
	students.push(new Student('박문수',98,98,97,96));
	students.push(new Student('장영실',97,98,97,96));
	students.push(new Student('김유신',96,98,97,96));
	students.push(new Student('이순신',95,98,97,96));
	
	//출력
	document.write('이름, 총점, 평균<br>');
	for(let i in students){
		document.write(students[i].toString() + '<br>');
	}
	
</script>
</body>
</html>

11. 실습

[실습]
생성자 함수(Account)를 이용해서 은행 계좌 생성하는 프로그램
속성 : 계좌번호, 예금주, 비밀번호, 잔고
메서드 : 입금 메서드(deposite), 출금 메서드(widthraw), 출력 메서드(toString)
실행 순서 --> 계좌 생성, 입금하기, 출금하기, 은행 정보 출력
[출력 예시]
계좌번호 : 010123
예금주 : 홍길동
잔고 : 1000원
<title>실습</title>
</head>
<body>
<script type="text/javascript">
	
	//생성자 함수 지정
	function Account(num,name,passwd,balance){
		//속성 지정
		this.계좌번호 = num;
		this.예금주 = name;
		this.비밀번호 = passwd;
		this.잔고 = balance;
		//메서드 지정
		this.deposite = function(money){ //입금하기
			this.잔고 += money;
		};
		this.withdraw = function(money){ //출금하기
			this.잔고 -= money
		};
		this.toString = function(){
			return '계좌번호 : ' + this.계좌번호 +'<br>'
					+ '예금주 : ' + this.예금주 + '<br>'
					+ '잔고 : ' + this.잔고 + '원';
		};
	}
	
	//객체 생성
	const account = new Account('010123','홍길동','1234',1000);
	document.write(account + '<br>');
	document.write('-------------<br>');
	
	//입금하기
	account.deposite(500);
	document.write(account + '<br>');
	document.write('-------------<br>');
	
	//출금하기
	account.withdraw(600);
	document.write(account + '<br>');
	
</script>
</body>
</html>

12. extention

  • 자바스크립트는 프로토타입을 이용하여 상속 구현
<title>상속</title>
</head>
<body>
<script type="text/javascript">

function Human(age){
	this.age = age; //프로토타입으로 정의되지 않아서 상속X
}
Human.prototype.type = '사람'; //속성(상속O)
Human.prototype.getType = function(){ //메서드(상속O)
	return this.type;
};
Human.prototype.getAge = function(){
	return this.age;
};

const human = new Human(20);
document.write('human.type : ' + human.type + '<br>'); //속성에 접근
document.write('human.age : ' + human.age + '<br>'); //속성에 접근
document.write('human.getType() : ' + human.getType() + '<br>'); //메서드 호출
document.write('human.getAge() : ' + human.getAge() + '<br>'); //메서드 호출
document.write('----------------------------------<br> ');

function Student(age){
	this.age = age;
}
//Human의 프로토타입에 정의된 속성 또는 메서드를 상속시킴
Student.prototype = Human.prototype; //상속
Student.prototype.constructor = Student; //생성자명을 Student로 유지(안하면 Human으로 바뀜)

const student = new Student(50);
document.write('student.type = ' + student.type + '<br>'); //상속에 의해 호출
document.write('student.age = ' + student.age + '<br>'); //상속에 의해 호출
document.write('student.getType() = ' + student.getType() + '<br>'); //상속에 의해 호출
document.write('studet.getAge() = ' + student.getAge()); //상속에 의해 호출

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

13. class

1)

<title>클래스의 정의</title>
</head>
<body>
<script type="text/javascript">

//클래스 선언
class Person{}

//익명 클래스 표현식
const Person = class{};

//기명 클래스 표현식
const Person = class MyClass{};

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

2)

<title>클래스의 정의</title>
</head>
<body>
<script type="text/javascript">

//클래스 선언
class Person{
	//생성자
	constructor(name){
		//인스턴스 생성 및 초기화
		//인스턴스 프로퍼티
		this.name = name;
	}
	//메서드
	sayHi(){
		document.write('Hi My name is ' + this.name);
	}
	//정적 메서드
	static sayHello(){
		document.write('Hello!');
	}
}

//인스턴스 생성
const me = new Person('Lee');
//인스턴스의 프로퍼티 참조
document.write(me.name + '<br>');
//메서드 호출
me.sayHi();
document.write('<br>');
//정적 메서드 호출
Person.sayHello();

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

0개의 댓글