[패스트캠퍼스 FE MGS] Day11(7월 11일/월- Javascript 클래스)

1sol·2022년 7월 14일

패스트캠퍼스 FE MGS

목록 보기
10/11

LEARN!!

  • 객체 데이터
  • 생성자 함수
  • this
  • 클래스
  • 상속

1. 객체 데이터의 구조

const honeybadger = {
  firstName: 'honey'
  lastName: 'Badger'
  getFullName: function(){
   return `${this.firstName} ${this.lastName}`
  }
}

console.log(honeybadger.getFullName());
  • 속성(property) : firstName, lastName
  • 메소드(method) : getFullName
  • 멤버(Member) : 속성과 메소드를 통틀어서 멤버라고 부름

2. 생성자 함수

function User(first, last){
  this.firstName = first;
  this.lastName = last;
}
User.prototype.getFullName = function () {
  return `${this.firstname} ${this.lastName}`
}

const honeybadger = new User('honey', 'badger');
const amy = new User('Amy', 'Clarke');
const neo = new User('Neo', 'Smith');

console.log(honeybadger.getFullName());
  • new 키워드를 통해서 생성하고 인자값을 넣어서 하나의 객체데이터를 생성하게 됨
  • 생성자 함수의 인스턴스란 생성자 함수로 실행한 결과를 반환해서 할당된 그 변수를 인스턴스라 한다. ( 위의 코드에서 honeybadger, amy, neo)
  • user라는 함수에 있는 prototype속성에 getFullName을 할당하여 함수를 만들어서 몇개의 객체를 만들던 이 함수는 메모리에 딱 한번만 만들어진다.
  • 따라서 amy.getFullName() 이라는 메소드는 user.prototype.getFullName 이라는 만들어진 함수를 참조하는것
  • 생성자 함수와 일반 함수들을 구분하기 위해 파스칼케이스를 사용해서 시작 첫 글자를 대문자로 작성한다!

prototype을 사용하여 new라는 키워드와 함께 인스턴스를 만들어내는 이러한 개념들을 자바스크립트의 클래스라고 한다.


3. 클래스

생성자함수를 클래스로 바꾸기

// 생성자 함수
function User(first, last){
  this.firstName = first;
  this.lastName = last;
}
User.prototype.getFullName = function () {
  return `${this.firstname} ${this.lastName}`
}


// 클래스로 바꾸기
class User{
  constructor(first, last){
    this.firstName = first;
    this.lastName = last;
  }
  getFullName(){
    return `${this.firstName} ${this.lastName}`
  }
}

const honeybadger = new User('honey', 'badger');
  • 생성자함수 사용은 현재 거의 쓰이지 않음
  • constructor라는 내부 함수를 사용해야함
  • 생성자 함수와 같이 new라는 키워드를 사용해서 객체를 만들수있음
  • honeybadgerUser클래스의 인스턴스가 된다.

4. 클래스 상속

class Vehicle {
 constructor(name, wheel){
   this.name = name
   this.wheel = wheel
 }
}

const myVehicle = new Vehicle('운송수단', 2)

class Bicycle extends Vehicle {
  constructor(name, wheel){
    super(name, wheel)
  }
}

const myBicycle = new Bicycle('삼천리', 2)
consol.log(myBicycle)

class Car extends Vehicle {
  constructor(name, wheel, license) {
   super(name, wheel)
   this.license = license
  }
}

const myCar = new Car('벤츠', 4, true)
console.log(myCar)
  • 상위 클래스 Vehicle
  • 상위 클래스 Vehicle을 상속해서 만든 Bicycle, Car 클래스
  • 부모클래스의 constructor를 사용하고 싶다면 super()를 통해 사용함
  • Car클래스와 같이 constructor안에 새롭게 추가할수있음

5. this

const honeybadger = {
  name: 'honeybadger'
  normal: function(){
    console.log(this.name)
  },
  arrow: () => {
    console.log(this.name)
  }
}
honeybadger.normal(); // 결과값: honeybadger
honeybadger.arrow(); // 결과값: undefined
  • this 라는 키워드를 통해서 객체 이름을 직접적으로 명시하지 않고 this를 통해 객체를 지칭할 수 있음
  • 일반(Normal) 함수는 호출 위치에 따라 this 정의!
  • 화살표(Arrow) 함수는 자신이 선언된 함수 범위에서 this 정의!
profile
be driven

0개의 댓글