Class
class student {
constructor(age, phone, city) {
this.age = age;
this.phone = phone;
this.city = city;
}
getInfo() {
return (
"나이는:" +
this.age +
",폰번호는:" +
this.phone +
",사는곳은:" +
this.city +
"이다"
);
}
}
let st = new student(30, 30, "seoul");
console.log(st.getInfo());
- java와 다른 객체지향 언어에서 많이 사용한 class이다. 사실 리액트에서 함수지향을 사용했기 때문에
js에서 class는 사용해본적이 별로없다
- 생성자를 이용해 this로 객체를 생성할시 해당 변수에 할당되도록 한다.
class Character {
constructor(hp, mp, atk) {
this.hp = hp;
this.mp = mp;
this.atk = atk;
}
getState() {
return this.hp + this.mp + this.atk;
}
static getAtk(n) {
return n.atk;
}
}
let ca = new Character(100, 100, 100);
console.log(ca);
console.log(Character.getAtk(ca));
- static으로 전역 함수를 만들면 java와 마찬가지로 class에서 직접 호출이 가능하다.
- 공용함수를 만들 때 매우 유용하다!
js에서도 이게 되네 ㄷㄷ
class Product {
constructor(name, price) {
this.name = name;
this.price = price;
}
get getName() {
return "production" + this.name;
}
set setPrice(price) {
this.price = price;
}
}
let pr = new Product("갤럭시 노트", 1000000);
console.log(pr);
console.log(pr.getName);
pr.setPrice=2000;
console.log(pr);
왜! 인텔리제이에선 getter setter자동으로 해주는데! vsc엔 없어!
- get,set 선언자를 붙임으로서 getter,setter를 만들 수 있다.
- setPrice에서 매개변수를 안에 파라미터로 전달하는 방식이 아닌 일반 오브젝트 객체를 바꾸는 식으로 바꾼다.
- 마찬가지로 getName도 함수형식인 getName()이 아니다
class Mother {
constructor(name, age) {
this.name = name;
this.age = age;
}
getInfo() {
return console.log(`내 이름은:${this.name} 나이는:${this.age}입니다.`);
}
}
let temp = new Mother("아무개", 30);
temp.getInfo();
class Child extends Mother {
}
let temp2 = new Child("나는 자식 ", 30);
temp2.getInfo();
- 상속이다.
- java와 마찬가지로 extends를 쓴다. 또한 함수를 공유하는것도 똑같다.
class Animal {
constructor(name) {
this.name = name;
this.speed = 0;
this.age = 20;
}
run(speed) {
this.speed += speed;
console.log(`${this.name}은 ${this.speed}로 달리는중 나는 부모의 함수임`);
}
stop() {
this.speed = 0;
console.log(`${this.name}이 멈춤`);
}
}
let ani = new Animal("동물");
ani.run(10);
ani.stop();
class Cat extends Animal {
run(speed) {
this.speed = speed;
console.log(
`${this.name}은 ${this.speed}로 달리는 중 나는 자식의 오버라이딩 함수임`
);
}
speak() {
console.log("take a look");
}
stop() {
super.stop();
this.speak();
}
}
let cat = new Cat("떼껄룩");
cat.run(10);
cat.stop();
- 상속을 받을 당시 overriding을 이용해 부모함수를 변경할 수 있다.
- 또한 super()를 사용하여 부모의 함수를 호출할 수 있다.
class Human {
constructor(name, age) {
this.name = name;
this.age = age;
}
}
class Man extends Human {
constructor(name, age) {
this.name = name;
this.age = age;
}
}
let ma= new Man('gg',30);
console.log(ma)
- 당연한 말이지만 자식이 이중으로 생성자를 생성하면 안된다!