패스트 캠퍼스 MGS 3기 - 4월 26일(JavaScript 클래스)

JY·2022년 4월 26일
0
post-thumbnail

💡 Keyword


  • js의 클래스 - 생성자와 this
  • 함수 종류에 따른 this의 정의
  • ES6 Classes
  • 상속(확장)



클래스

1. 생성자 함수(prototype)


다음 예제에서 객체 데이터를 하나 만들 때마다 메모리에 할당되는데 함수는 로직이 똑같음에도 불구하고 우리가 만들어내는 객체 데이터의 개수만큼 함수도 메모리에 할당된다. 그래서 이때 사용되는 것이 '클래스'이다.

const jisung = {
  firstName: 'Ji-sung',
  lastName: 'Park',
  getFullName: function () {
    // this 대신 printName으로 직접 명시할 수도 있지만
    // 변경될 수도 있으므로 this를 사용하는 것을 권장
    return `${this.firstName} ${this.lastName}`
  }
}
console.log(jisung.getFullName())

const doyoung = {
  firstName: 'Do-young',
  lastName: 'Kim',
  getFullName: function () {
    return `${this.firstName} ${this.lastName}`
  }
}
console.log(doyoung.getFullName())

const mark = {
  firstName: 'Mark',
  lastName: 'Lee',
  getFullName: function () {
    return `${this.firstName} ${this.lastName}`
  }
}
console.log(mark.getFullName())

👉 실행 결과


❗ 클래스를 이용해서 수정해보자.

// 함수 이름을 대문자로 적는다는 것(Pascal case)은
// new라는 키워드와 함께 생성자 함수로 사용된다는 의미이다.
function User(first, last) {
  this.firstName = first
  this.lastName = last
}
// 이 부분의 함수는 메모리에 한 번만 만들어진다. (prototype으로 지정)
User.prototype.getFullName = function () {
  return `${this.firstName} ${this.lastName}`
}

// user를 '생성자 함수'라고 한다.
// 생성자 함수로 실행한 결과를 반환해서 할당된 변수를 '인스턴스'라고 한다.
const jisung = new User('Ji-sung', 'Park')
const mark = new User('Mark', 'Lee')
const doyoung = new User('Do-young', 'Kim')

// getFullName 함수를 '참조'한다! 매번 메모리를 할당하지 않는다.
console.log(jisung.getFullName())
console.log(mark.getFullName())
console.log(doyoung.getFullName())

👉 실행 결과

2. this


  • 일반(Normal) 함수는 호출 위치에 따라 this를 정의한다.
  • 화살표(Arrow) 함수는 자신이 선언된 함수 범위에서 this를 정의한다.

일반 함수

기본적으로 normal이라는 메소드는 heropy라는 객체 데이터 내부에서 실행된다.
heropy.normal()에서 호출되고, normal 앞에 있는 객체 데이터는 heropy이므로 이것이 곧 this이고 거기에서 name 부분을 꺼내서 사용하는 것이다.

화살표 함수

화살표 함수의 내부에서 this는 현재 코드에서 무엇인지 정확하게 알 수 없고, 그곳에서 name이라는 속성을 찾으려고 하여 undefined가 출력된 것이다.


함수를 할당하고 있다. normalarrow의 뒤에서 ()가 열려서 함수가 실행(호출)되는 것이 아니라 normalarrow 부분에 있는 데이터를 amynormalarrow에 할당하는 것이다.

일반 함수의 경우는 다음과 같다.

타이머 함수를 만들 때, thissetTimeout에서 정의되는 것이 아닌 명확하게 우리가 작성한 특정한 범위에서 this가 정의될 수 있도록 화살표 함수를 사용하는 것이 좋다.

3. ES6 Classes


어떤 이름이 나오고 소괄호와 함께 중괄호가 열리고 닫히면 이는 function 키워드를 사용하는 일반 함수로 만들어진 개념과 동일하다.

normal: function() {
  console.log(this.name)
}

다음은 위의 코드를 클래스를 사용해서 만든 것이다. 같은 동작을 수행한다.

normal() {
 console.log(this.name)
}

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

const jisung = new User('Ji-sung', 'Park')
console.log(jisung.getFullName())

다음은 위의 코드를 클래스를 사용해서 만든 것이다. 같은 동작을 수행한다.

class User {
  constructor(first, last) {
    this.firstName = first
    this.lastName = last
  }
  getFullName() {
    return `${this.firstName} ${this.lastName}`
  }
}

const jisung = new User('Ji-sung', 'Park')
console.log(jisung.getFullName())

4. 상속(확장)


클래스를 만들 때 이미 정의가 되어있는 내용을 상속, 확장(extends)해서 쉽게 구현할 수 있다.
클래스를 사용한다는 것은 미리 만들어진 어떠한 정보에 추가적으로 살을 붙여가면서 새로운 기능을 확장한다고 볼 수 있다.

super가 있는 자리에서 Vehicle이 실행된다.

profile
🙋‍♀️

0개의 댓글