function
키워드 대신 class
키워드를 사용합니다.class 클래스명{
constructor(){
this.속성명 = 값;
}
메서드명(){
}
}
class Car {
constructor(name){
this.brand = name;
}
}
const 인스턴스명 = new 클래스명();
class Car {
constructor(name){
this.brand = name;
}
}
const myCar = new Car("Audi");
console.log(myCar.brand);
const Car = class {
constructor(name){
this.brand = name;
}
}
const myCar = new Car("Audi");
console.log(myCar.brand);
속성은 constructor()메서드 내부에 작성됩니다.
class 클래스명{
constructor(){
this.속성명 = 값;
}
}
메서드는 class 코드 블록 내부에 작성됩니다.
class 클래스명{
메서드명(){
}
}
class Car {
constructor(name){
this.brand = name;
}
//present라는 메서드 추가
present(){
return '나는 ' + this.brand + '를 소유하게 되었다.';
}
}
//새로운 객체 생성
const myCar = new Car("Audi");
// 생성자 함수는 객체 초기화 할때 자동으로 호출
console.log(myCar.brand);
console.log(myCar.present());
- 상속 : 부모 클래스의 멤버(필드,메서드)를 자식 클래스에게 물려주는 것입니다.
- 부모 클래스 : 상위 클래스, 슈퍼클래스 라고도 부릅니다.
- 자손클래스 : 하위클래스,자식클래스,파생클래스 라고도 부릅니다.
class 자식클래스 extends 부모클래스{
}
super()
메서드를 사용함으로써, 부모의 생성자 메서드를 호출하고 부모의 메서드와 속성을 받아서 사용 가능해집니다. class Car {
constructor(name){
this.brand = name;
}
//present라는 메서드 추가
present(){
return '나는 ' + this.brand + '를 소유하게 되었다. ';
}
}
//model만 정의할 자손 클래스
class Model extends Car {
constructor(name, mod){
super(name); //super()메서드는 부모 클래스를 나타냄
this.model = mod;
}
show(){
return this.present() + '그것은 ' + this.model + '이다.';
}
}
const myCar1 = new Model("BMW","X7");
const myCar2 = new Model("Ford","Mustang");
console.log(myCar1.show());
console.log(myCar2.show());