Skills/JavaScript
221226 class_01.html 객체 클래스
개발자 윤구나
2022. 12. 26. 12:01
<!DOCTYPE html>
<html lang="ko">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Class</title>
<script>
document.addEventListener("DOMContentLoaded", () => {
// Class: 객체를 효율적으로 다루기 위한 문법(방법)
// 객체의 추상화
const students = [];
students.push({ name: "kim", kor: 100, eng: 100, mat: 100 }); // students[0].name = 'kim'
students.push({ name: "lee", kor: 95, eng: 95, mat: 95 });
students.push({ name: "woo", kor: 90, eng: 90, mat: 90 });
console.log(JSON.stringify(students, null, 2));
let output = "name\t total\t average\n";
// for(let i=0; i<students.length; i++)로 사용가능
for (const student of students) {
// student 대신 item, value 사용도 괜찮음.
let sum = student.kor + student.eng + student.mat;
let average = sum / 3;
output += `${student.name}\t\t ${sum}점\t ${average}점\n`; // \t는 tab!
}
console.log(output);
// 객체처리함수 - 함수분리(객체외부함수)
// const students = [];
students.push({ name: "kim", kor: 100, eng: 100, mat: 100 });
students.push({ name: "lee", kor: 95, eng: 95, mat: 95 });
students.push({ name: "woo", kor: 90, eng: 90, mat: 90 });
console.log(JSON.stringify(students, null, 2));
function getSum(student) {
return student.kor + student.eng + student.mat;
}
function getAverage(student) {
return getSum(student) / 3;
}
// let output = "name\t sum\t average\n";
for (const student of students) {
output += `${student.name}\t\t ${getSum(student)}점\t ${getAverage(
student
)}점\n`;
}
console.log(output);
// 객체처리함수 - 객체 내부에서 함수 사용
// const students = [];
students.push({ name: "kim", kor: 100, eng: 100, mat: 100 });
students.push({ name: "lee", kor: 95, eng: 95, mat: 95 });
students.push({ name: "woo", kor: 90, eng: 90, mat: 90 });
console.log(JSON.stringify(students, null, 2));
for (const student of students) {
student.getSum = function () {
return this.kor + this.eng + this.mat;
// this 사용할거라면 화살표함수 사용안됨
};
student.getAverage = function () {
return this.getSum() / 3;
};
}
// let output = "name\t sum\t average\n";
for (const student of students) {
output += `${
student.name
}\t\t ${student.getSum()}점\t ${student.getAverage()}점\n`;
}
console.log(output);
// 객체 생성자 함수 - 객체 데이터의 속성, 메서드, 객체 선언 후 사용
// ★추천사용법 (하지만 앞의 내용도 사용할 수 있어야함)
function createStudent(name, kor, eng, mat) {
return {
name: name,
kor: kor,
eng: eng,
mat: mat,
getSum() {
return this.kor + this.eng + this.mat;
},
getAverage() {
return this.getSum() / 3;
},
toString() {
return `${
this.name
}\t\t ${this.getSum()}점\t ${this.getAverage()}점\n`;
},
}; // return
} // createStudent()
// const students = [];
students.push(createStudent("kim", 100, 100, 100));
students.push(createStudent("lee", 95, 95, 95));
students.push(createStudent("woo", 90, 90, 90));
// let output = "name\t sum\t average\n";
for (const student of students) {
output += student.toString();
}
console.log(output);
});
</script>
</head>
<body></body>
</html>