✍️ 면접 때 class 함수에 관한 질문을 받았었다. 객체지향형 프로그래밍 하면 class기반이 대표적이다. (Java, C++, C#, Python, PHP, Ruby, Object-C) 반면에 javascript는prototype 기반이다.(생성자 함수) es6 부터 javascript 도 class 문법을 지원 하기 시작 하였다. extends와 super 를 통한 상속, Object.assign을 이용해 믹스인 하는 방법 등 유용하게 쓸 것 같다.
class User {
constructor(name){
this.name = name;
}
introduceMyself(){
console.log(`my name is ${this.name}`);
}
}
let user = new User('mangojang');
user.introduceMyself() // my name is mangojang;
class User {
constructor(name){
this.name = name;
}
get name(){
return this._name;
}
set name(value){
if (!value.trim().length){
alert('이름을 다시 확인 해 주세요.')
return;
}
this._name = value;
}
}
let user = new User('mangojang');
console.log(user.name); // mangojang
user = new User(" "); // 이름으 다시 확인 해 주세요.
속성 명 = 값
class Mangojang {
name = 'mangojang'
introduceMyself(){
console.log(`my name is ${this.name}`);
}
}
new Mangojang().introduceMyself(); // my name is mangojang
class Button {
constructor(value) {
this.value = value;
}
click() {
alert(this.value);
}
}
let button = new Button("click!");
setTimeout(button.click, 1000); // undefined
function 으로 한번 더 감싸서 스코프를 준다.
setTimeout(()=>button.click, 1000);
.bind 로 Button 바인딩
let click = button.click.bind(button);
setTimeout(click 1000);
클래스 필드 이용하기
class Button {
constructor(value) {
this.value = value;
}
click = () => {
alert(this.value);
}
}
let button = new Button("click!");
setTimeout(button.click, 1000); // click!
class Animal {
constructor(name) {
this.speed = 0;
this.name = name;
}
run(speed) {
this.speed = speed;
alert(`${this.name}가 속도 ${this.speed}로 달립니다.`);
}
stop() {
this.speed = 0;
alert(`${this.name}가 멈췄습니다.`);
}
}
let animal = new Animal("동물");
class Rabbit extends Animal {
// Animal run 메서드를 오버라이딩(= 덮어쓰기) 함 .
run(speed) {
this.speed = speed + 10;
alert(`${this.name}가 속도 ${this.speed}로 달립니다.`);
}
// hide 메서드 확장
hide() {
alert(`${this.name} 이/가 숨었습니다!`);
}
}
let rabbit = new Rabbit("흰 토끼");
// Animal 속성을 상속 받은 Rabbit은 speen, name 속성과, run, stop 메서드를 포함하고 있음.
rabbit.run(5); // 흰 토끼 은/는 속도 15로 달립니다.
rabbit.hide(); // 흰 토끼 이/가 숨었습니다!
🚫 화살표 함수는 super를 지원 하지 않음.
class Animal {
constructor(name) {
this.speed = 0;
this.name = name;
}
run(speed) {
this.speed = speed;
alert(`${this.name}가 속도 ${this.speed}로 달립니다.`);
}
stop() {
this.speed = 0;
alert(`${this.name}가 멈췄습니다.`);
}
}
class Rabbit extends Animal {
hide() {
alert(`${this.name}가 숨었습니다!`);
}
stop() {
super.stop(); // 부모 클래스의 메서드 상속
this.hide(); // 확장
}
}
let rabbit = new Rabbit("흰 토끼");
rabbit.run(5); // 흰 토끼가 속도 5로 달립니다.
rabbit.stop(); // 흰 토끼가 멈췄습니다. 흰 토끼가 숨었습니다!
class Animal {
constructor(name) {
this.speed = 0;
this.name = name;
}
// ...
}
class Rabbit extends Animal {
constructor(name, earLength) { // earLength 인자 추가
super(name);
this.earLength = earLength;
}
// ...
}
let rabbit = new Rabbit("흰 토끼", 10);
alert(rabbit.name); // 흰 토끼
alert(rabbit.earLength); // 10
▶️ 내부 this의 사용이 필요 없는 경우, utility 함수를 정의 할 때 주로 사용.
class Triple {
static triple(n) {
n = n || 1; //비트연산이 아니어야 합니다.
return n * 3;
}
}
class BiggerTriple extends Triple {
static triple(n) {
return super.triple(n) * super.triple(n);
}
}
console.log(Triple.triple()); // 3
console.log(Triple.triple(6)); // 18
console.log(BiggerTriple.triple(3)); // 81
var tp = new Triple();
console.log(BiggerTriple.triple(3)); // 81 (부모의 인스턴스에 영향을 받지 않습니다.)
console.log(tp.triple()); // 'tp.triple은 함수가 아닙니다.'.
console.log(tp.constructor.triple(4)); // 12
class Article {
static publisher = "Ilya Kantor";
}
alert( Article.publisher ); // Ilya Kantor
class CoffeeMachine {
#waterAmount = 0;
get waterAmount() {
return this.#waterAmount;
}
set waterAmount(value) {
if (value < 0) throw new Error("물의 양은 음수가 될 수 없습니다.");
this.#waterAmount = value;
}
}
let machine = new CoffeeMachine();
machine.waterAmount = 100; // setter 실행
alert(machine.waterAmount); // 100
alert(machine.#waterAmount); // Error
class CoffeeMachine {
_waterAmount = 0;
set waterAmount(value) {
if (value < 0) throw new Error("물의 양은 음수가 될 수 없습니다.");
this._waterAmount = value;
}
get waterAmount() {
return this._waterAmount;
}
constructor(power) {
this._power = power;
}
}
// 커피 머신 생성
let coffeeMachine = new CoffeeMachine(100);
// 물 추가
coffeeMachine.waterAmount = -10; // Error: 물의 양은 음수가 될 수 없습니다.
class CoffeeMachine {
// ...
constructor(power) {
this._power = power;
}
get power() {
return this._power;
}
}
// 커피 머신 생성
let coffeeMachine = new CoffeeMachine(100);
alert(`전력량이 ${coffeeMachine.power}인 커피머신을 만듭니다.`); // 전력량이 100인 커피머신을 만듭니다.
coffeeMachine.power = 25; // Error (setter 없음)
obj instanceof Class
// 믹스인
let sayHiMixin = {
sayHi() {
alert(`Hello ${this.name}`);
},
sayBye() {
alert(`Bye ${this.name}`);
}
};
// 사용법:
class User {
constructor(name) {
this.name = name;
}
}
// 메서드 복사
Object.assign(User.prototype, sayHiMixin);
// 이제 User가 인사를 할 수 있습니다.
new User("Dude").sayHi(); // Hello Dude!