class Person{
}
var kim = new Person();
console.log('kim', kim); // kim Person{}
Person이라는 class를 만들어서 생성자 함수를 실행하면 Person이라는 인스턴스가 생성된다
class Person{
constructor(name, first, second){
this.name = name;
this.first = first;
this.second = second;
}
}
var kim = new Person('kim', 10, 20);
console.log('kim', kim); // Person { name: 'kim', first: 10, second: 20 }
class Person{
constructor(name, first, second){
this.name = name;
this.first = first;
this.second = second;
}
sum(){
return 'prototype : '+(this.first+this.second);
}
}
var kim = new Person('kim', 10, 20);
kim.sum = function(){
return 'this : '+(this.first+this.second);
}
var lee = new Person('lee', 10, 10);
console.log("kim.sum()", kim.sum()); // kim.sum() this : 30
console.log("lee.sum()", lee.sum()); // lee.sum() prototype : 30
class Person{
constructor(name, first, second){
this.name = name;
this.first = first;
this.second = second;
}
sum(){
return this.first+this.second;
}
위 코드에서 평균을 구하는 메소드를 추가하고 싶을 때
avg(){
return (this.first+this.second)/2;
}
이렇게 새로운 함수를 만들어서 constructor에 넣어줄 수도 있지만 항상 그럴수는 없다.
이럴 때 새로운 클래스를 정의해서 해결할 수 있다.
class PersonPlus{
constructor(name, first, second){
this.name = name;
this.first = first;
this.second = second;
}
sum(){
return this.first+this.second;
}
avg(){
return (this.first+this.second)/2;
}
그러나 중복이 발생하게 되는데, 이런 중복을 제거하기 위해 상속을 사용한다.
class Person{
constructor(name, first, second){
this.name = name;
this.first = first;
this.second = second;
}
sum(){
return this.first+this.second;
}
}
class PersonPlus extends Person{
avg(){
return (this.first+this.second)/2;
}
}
var kim = new PersonPlus('kim', 10, 20);
console.log("kim.sum()", kim.sum()); // kim.sum() 30
console.log("kim.avg()", kim.avg()); // kim.avg() 15
extends Person에 의해 기존 Person 클래스의 요소들이 상속된다. → 중복되는 요소들을 지워도 된다.