클래스

uoayop·2021년 2월 27일
0

JavaScript

목록 보기
12/24
post-thumbnail

Javascript

클래스

🔧 ES6 에 새로 추가된 문법이다. 좀 더 객체지향에 가까워졌다.

  • 객체를 만들 수 있는 새로운 방법이다.

클래스를 만들 수 있는 방법

1. 함수처럼 선언적 방식

  • 선언적 방식이지만 호이스팅은 일어나지 않는다.
  • 함수 같은 경우는 호이스팅이 일어날 수 있다.
class A {}

console.log(new A());
// A{}

new C();
class C{}
// error : C is not defined

2. class 표현식을 변수에 할당

const B = class {};

console.log(new B());
//B{}

생성자 (constructor)

  • 최초의 초기값을 객체로 넣어줄 수 있다.
class A{
  constructor(){
    console.log('constructor');
  }
}

console.log(new A());
// 출력:
// constructor 
// A {}

Class B{
  constructor(name,age){
    console.log('constructor',name,age);
  }
}

console.log(new B('doyeon',23));
// 출력:
// constructor doyeon 23
// B {}

멤버변수

  • 객체의 프로퍼티
class A{
  constructor(name,age){
    this.name=name;
    this.age=age;
  }
}

console.log(new A('doyeon',23));
// A { name:'doyeon',age:23 }

class B{
  name;
  age;
}

console.log(new B())
// node 12버전 이상부터만 사용 가능하다
// $nvm use 12.11.1
// 출력: B { name:undefined, age:undefined }

class C{
  name = 'no name';
	age = 0;
	constructor(name,age){
    this.name=name;
    this.age=age;
  }
}

console.log(new C('doyeon',23));
// C { name:'doyeon',age:23 }

// 멤버함수 만드는 두가지 방법

class A{
  hello(){
    console.log('hello',this);
  }
  
  hello2 = () => {
    console.log('hello2',this);
  }
}

new A().hello();
// hello1 A { hello2: [Function: hello2] }
new A().hello2();
// hello2 A { hello2: [Function: hello2] }

class B{
  name = 'doyeon';

	hello(){
    console.log('hello',this.name);
  }
}

new B().hello();
// hello doyeon

get, set

  • 외부에서 내부의 멤버변수에 접근할 때 사용
class A{
  _name = 'no name';
	get name(){
    return this._name + '@@@';
  }
	set name(value){
    this._name = value + '!!!';
  }
}

const a = new A();
console.log(a);
// A { _name:'no name' }

// setter
a.name = 'doyeon';
console.log(a);
// A {_name:'doyeon!!!'}

// getter
console.log(a.name);
// doyeon!!!@@@

// 직접 접근
console.log(a._name);
// doyeon!!!

static 변수, 함수

  • 객체가 아닌 직접 클래스를 통해서 사용하는 변수와 함수
class A{
  static age = 37;
	static hello(){
    console.log(A.age);
  }
}

console.log(A, A.age);
// [Function: A] {age: 37} 37
A.hello();
//37

class B{
  age = 37;
	static hello(){
    console.log(this.age);
  }
}

// static age가 아니기 때문에 undefined가 뜨고,
// B.age가 아닌 this.age를 출력해서 undefined가 뜬다.
console.log(B, B.age);
// [Function: B] undefined
B.hello();
// undefined
new B.hello();
//error: hello is not a function
// hello는 static 함수여서, 인스턴스엔 속하지 않는 함수다.


class C{
  static name='이 클래스의 이름은 C가 아니다.'
}

console.log(C);
// [Function: 이 클래스의 이름은 C가 아니다.] {name:'이 클래스의 이름은 C가 아니다.'}
// 🔥 static name이 클래스의 이름을 의미하는 것을 알 수 있다.

클래스 상속하기 ; extends

  • 클래스 상속의 기본
class Parent{
  name = 'Kim'
	hello() {
    console.log('hello',this.name);
  }
}

class Chile extends Parent{}

const p = new Parent();
const c = new Child();

console.log(p,c);
// Parent {name:'Kim'} Child {name:'Kim'}

c.hello()
c.name = 'doyeon'
c.hello()
// hello Kim
// hello doyeon

오버라이딩

  • 클래스의 상속 멤버 변수 및 함수 오버라이딩 : 추가하는 개념
  • 부모에서 구현된 함수나 변수가 자식에게 그대로 같은 이름으로 구현을 시키면 그것을 오버라이드 한다고 한다.
    • 🔄 자식이 부모의 요소를 덮어씌우는 느낌이다.
    • 🆕 부모에 없는 요소인 경우엔 추가 된다.
class Parent{
    name = 'Kim'
    hello() {
    console.log('hello',this.name);
  }
}

class Child extends Parent{
  //부모에는 age 요소가 없음
    age = 23;
    hello() {
    console.log('hello',this.name, this.age);
  }
}

const p = new Parent();
const c = new Child();

console.log(p,c);
// Parent {name:'Kim'} Child {name:'Kim', age:23}

c.hello()
// hello Kim 23
// 부모의 함수가 덮어씌워졌다.
c.name = 'doyeon'
c.hello()
// hello doyeon 23

super

  • 자식이 constructor에 뭔가 추가하고 싶을 때, super를 호출해야 한다.
class Parent{
  name;
  
  constructor(name){
    this.name = name;
  }
  hello(){
    console.log('hello',this.name);
  }
}

class Child extends Parent{
  age;
  
  constructor(name,age){
    // 부모에서 먼저 constructor로 name을 할당할 수 있도록 super를 호출한다.
    
    // 🔥 자식이 this를 사용하기 전에 반드시 super를 호출하기
    // super는 부모의 constructor와 동일하다.
    super(name);
    this.age = age;
  }
  
  hello(){
    console.log('hello',this.name,this.age);
  }
}

const p = new Parent('Kim');
const c = new Child('Kim',23);

console.log(p,c);
// Parent {name:'Kim'} Child {name:'Kim', age: 23}

class Animal {
  constructor(type, name, sound) {
    this.type = type;
    this.name = name;
    this.sound = sound;
  }
  say() {
    console.log(this.sound);
  }
}

class Dog extends Animal {
  constructor(name, sound) {
    super("개", name, sound);
  }
}

const dog = new Dog("멍멍이", "멍멍");
dog.say();
//출력: 멍멍

static 변수 상속받기

class Parent{
  static age = 30;
}

class Child extend Parent{}

console.log(Parent.age,Child.age);
//30 30 : static 변수가 잘 상속된 것을 볼 수 있다.
profile
slow and steady wins the race 🐢

0개의 댓글