반응형
Class
Class 문법을 제공한다. constructor 메소드도 사용할 수 있고 extends를 통해서 클래스 상속도 가능하다.
class Person {
constructor (id, name) {
this.id = id
this.name = name
}
toString() {
return `(${this.id}, ${this.name})`
}
}
class Student extends Person {
constructor (id, name, age) {
super(id, name)
this.age = age
}
toString() {
return super.toString() + ' and ' + this.age
}
}
Setter/Getter
class Person {
constructor (id, name) {
this.id = id;
this.name = name;
}
getId(){
return this.id;
}
getName(){
return this.name;
}
setId(newId){
this.id = newId;
}
setName(newName){
this.name = newName;
}
toString() {
return `(id = ${this.id}, name = ${this.name})`;
}
}
class Student extends Person {
constructor (id, name, age) {
super(id, name);
this.age = age;
}
getAge(){
return this.age;
}
setAge(newAge){
this.age = newAge;
}
toString() {
return super.toString() + ' and age = ' + this.age;
}
}
let person = new Person('person', '사람');
console.log('--------------Person--------------');
console.log(person.toString()); // (id = person, name = 사람)
person.setId('set_person');
person.setName('set_name');
console.log(person.toString()); // (id = set_person, name = set_name)
let student = new Student('student', '학생', 25);
console.log('--------------student--------------');
console.log(student.toString()); // (id = student, name = 학생 and age = 25)
student.setId('set_person');
student.setName('set_name');
student.setAge(30);
console.log(student.toString()); // (id = set_person, name = set_name and age = 30)
console.log('--------------student.get--------------');
console.log('student.getId() : '+student.getId()); // student.getId() : set_person
console.log('student.getName() : '+student.getName()); // student.getName() : set_name
console.log('student.getAge() : '+student.getAge()); // student.getAge() : 30
console.log('--------------student.field--------------');
console.log('student.id : '+student.id); // student.id : set_person
console.log('student.name() : '+student.name); // student.name() : set_name
console.log('student.age() : '+student.age); // student.age() : 30
반응형
'TIL > JavaScript' 카테고리의 다른 글
[ECMASciprt6+ Features] 5. Arrow Functions (0) | 2021.07.22 |
---|---|
[ECMASciprt6+ Features] 4. let & const (0) | 2021.07.22 |
[ECMAScript6+를 위한 보충학습] 2. Callback (0) | 2021.07.21 |
[ECMAScript6+를 위한 보충학습] 1. EventLoop (0) | 2021.07.21 |
ECMAScript6+ (0) | 2021.07.21 |