class생성하기
class Person{
}
let kim = new Person();
console.log(kim) // Person {}
constructor(생성자)
class Person {
constructor(name,age,city){
this.name = name;
this.age = age;
this.cuty = city;
}
}
let kim = new Person('kim','24','seoul');
console.log(kim); //Person {name : 'kim', age:'24', city:'seoul'}
constructor(parameter1, parameter2 ... )
메서드
class Person {
constructor(name,age,city){
this.name = name;
this.age = age;
this.city = city;
}
//메서드생성
nextYearAge(){
return Number(this.age) + 1;
}
}
let kim = new Person('kim','24','seoul');
let park = new Person('park', '31', 'busan');
// 외부 메서드 생성
kim.eat = function() {
return 'apple'
}
console.log(kim.nextYearAge()); //25
console.log(kim.eat()); //apple
console.log(park.eat()); // Error!!
extends
class Person {
constructor(name,age,city){
this.name = name;
this.age = age;
this.city = city;
}
//메서드생성
nextYearAge(){
return Number(this.age) + 1;
}
}
class introducePerson extends Person{
inrtoduce() {
return `저는 ${this.city}`에 사는 ${this.name} 입니다.`
}
}
let kim = new introducePerson('kim','24','seoul');
console.log(kim.introduce()) //저는 seoul에 사는 kim입니다.
class 자식 extends 부모
super
class Person {
constructor(name,age,city){
this.name = name;
this.age = age;
this.city = city;
}
//메서드생성
nextYearAge(){
return Number(this.age) + 1;
}
}
class introducePerson extends Person{
constructor(name, age, city, futureHope){
super(name, age, city);
this.futureHope = futureHope
}
inrtoduce() {
return `저는 ${this.city}`에 사는 ${this.name} 입니다. 내년엔 ${super.nextYearAge()}살이며, 장래희망은 ${this.futureHope}입니다.`
}
}
let kim = new introducePerson('kim','24','seoul','개발자');
let park = new introducePerson('park','28','suwon','디자이너');
console.log(kim.introduce()); //저는 seoul에 사는 kim입니다. 내년엔 25살이며, 장래희망은 개발자입니다.
console.log(park.introduce()); //저는 suwon에 사는 park입니다. 내년엔 29실이며, 장래희망은 디자이너입니다.