programming/javascript
생활코딩 자바스크립트 class 강의를 보고 만든 예제
FaustK
2019. 8. 24. 21:06
class Students {
constructor (name, scoreA, scoreB) {
this.name = name;
this.scoreA = scoreA;
this.scoreB = scoreB;
}
sum () {
return (this.scoreA + this.scoreB);
}
info () {
return `name: ${this.name}, total: ${this.sum()}`;
}
}
var stu001 = new Students('mina', 100, 70);
var stu002 = new Students('lily', 90, 60);
console.log(stu001); // Students { name: 'mina', scoreA: 100, scoreB: 70 }
console.log(stu002); // Students { name: 'lily', scoreA: 90, scoreB: 60 }
console.log(stu001.sum()); // 170
console.log(stu002.sum()); // 150
console.log(stu001.info()); // name: mina, total: 170
console.log(stu002.info()); // name: lily, total: 150
// stu002.sum 변경
stu002.sum = function () {
return (this.scoreA + this.scoreB + 10);
}
console.log(stu002.info()); // name: lily, total: 160
자바스크립트 class 강의를 보고 만든 예제
class 기능은 es6 부터 추가된 기능이라고 한다.
말이 기능이지 사실은 흉내내는 것이라고 한다.
https://www.opentutorials.org/module/4047/24616
class에서 객체의 method 구현하기 - JavaScript 객체 지향 프로그래밍
수업소개 class를 통해서 객체를 생성할 때 모든 객체가 공유하는 공통(prototype)의 객체를 생성하는 방법을 소개합니다. 강의 코드 class.js (변경사항) class Person{ constructor(name, first, second){ this.name = name; this.first = first; this.second = second; } sum(){ return 'prototype : '+(this.first+this.sec
www.opentutorials.org
super 예제
class Students {
constructor (name, scoreA, scoreB) {
this.name = name;
this.scoreA = scoreA;
this.scoreB = scoreB;
}
sum () {
return (this.scoreA + this.scoreB);
}
}
class ExtentionStudents extends Students {
constructor (name, scoreA, scoreB, scoreC) {
super(name, scoreA, scoreB);
this.scoreC = scoreC;
}
total () {
return (super.sum() + this.scoreC);
}
}
var stu004 = new ExtentionStudents('rose', 100, 80, 60);
console.log(stu004); // { name: 'rose', scoreA: 100, scoreB: 80, scoreC: 60 }
console.log(stu004.total()); // 240