Developer/Javascript
자바스크립트 Class 이해하기
jaddong
2021. 9. 7. 18:09
320x100
- Classes are essentially blueprints for objects.
- Class는 Object의 필수적인 설계이다.
- Class는 class 이름이 있고 프로퍼티와 메소드를 둘 다 가지고 있을 수 있다.
- constructor 디폴트 메소드로 해당 class를 인스턴스화할 때마다 실행된다.
class Human {
constructor(){
this.gender = 'male';
}
printGender() {
console.log(this.gender)
}
}
class Person extends Human {
constructor(){
super(); // extends를 쓸 때 이것이 없으면 상의 클래스인 Human의 constructor가 실행되지 않아 에러가 발생한다.
this.name = 'Max';
this.gender = 'female' // 이게 없으면 'male' 이 출력됨
}
printName() {
console.log(this.name);
}
}
var person = new Person();
person.printName(); // 'Max'
person.printGender(); // 'female'
아래는 constructor가 없어지고, arrow function이 추가된 ES7 버전이다.
class Human {
gender = 'male';
printGender = () => {
console.log(this.gender)
}
}
class Person extends Human {
name = 'Max';
gender = 'female' // 이게 없으면 'male' 이 출력됨
printName = () => {
console.log(this.name);
}
}
var person = new Person();
person.printName(); // 'Max'
person.printGender(); // 'female'
반응형