"Boldness has genius, power, and magic in it." - Johann Wolfgang von Goethe

JavaScript

[JS] JavaScript 클래스(class) 정리

Toproot 2021. 7. 17. 23:58
728x90
728x90

 

🧀 1. 생성자 함수(prototype)

 

  • Javascript에서는 객체를 상속하기 위하여 프로토타입이라는 방식을 사용합니다.
  • 프로토타입 체인에서 한 객체의 메소드와 속성들이 다른 객체로 복사되는 것이 아님을 재차 언급합니다.
  • 체인(-)을 타고 올라가며 접근할 뿐입니다.
  • 같은 내용의 메소드가 반복되면 클래스를 활용!

const heropy = {
  firstName: 'Heropy', // 속성 혹은 멤버
  lastName: 'Park',
  getFullName: function () { // 메소드
    return `${this.firstName} ${this.lastName}`
    // this : 현재 객체를 지칭
  }
}

console.log(heropy)
console.log(heropy.getFullName())
  • 생성자 함수는 파스칼케이스 사용해서 작성.
  • prototype : getFullName만 한번 사용하여 메모리를 효율적으로 활용
  • new : 생성자 함수 (하나의 객체 데이터 생성)
  • 인스턴스 : new로 생성된 함수를 할당받은 변수
  • {} => 리터럴
// 생성자 함수는 파스칼케이스 사용해서 작성.
function User(first, last) {
  this.firstName = first
  this.lastName = last
}
// prototype : getFullName만 한번 사용하여 메모리를 효율적으로 활용
User.prototype.getFullName = function () {
  return `${this.firstName} ${this.lastName}`
}

// new : 생성자 함수 (하나의 객체 데이터 생성)
// 인스턴스 : new로 생성된 함수를 할당받은 변수
const heropy = new User('Heropy', 'Park')

console.log(heropy.getFullName())

 

🧀  2. this

 

  • this
  • 일반(Normal) 함수는 호출위치에서 따라 this 정의!
  • 화살표(Arrow) 함수는 자신이 선언된 함수 범위에서 this 정의!
  • 상황에 따라 구분해서 사용하기.

const heropy = {
  name: 'Heropy',
  // 일반함수
  normal: function () {
    console.log(this.name)
  },
  // 화살표함수
  arrow: () => {
    console.log(this.name)
  }
}
heropy.normal()
heropy.arrow()

const amy = {
  name: 'Amy',
  // 실행하는 것이 아니라 함수자체를 할당.
  normal: heropy.normal,
  arrow: heropy.arrow
}

// amy.normal()
// amy.arrow()
// 생성자 함수
function User (name) {
  this.name = name
}
User.prototype.normal = function () {
  console.log(this.name)
}
User.prototype.arrow = () => {
  console.log(this.name)
}

// heropy 인스턴스
const heropy = new User('Heropy')

// 함수 호출
heropy.normal() // heropy => User => this.name
heropy.arrow() // 현재 자신이 선언된 함수 범위에서 this를 찾고 없으면 undefined
const timer = {
  name: 'Heropy!',
  // 일반 함수
  timeout: function () {
    // 콜백함수
    // 이런식으로 함수 내에서 함수를 사용할 때 함수범위의 this를 사용한다면
    // 화살표함수를 사용.. 일반함수는 현재 setTimeout함수 내에서 정의된 this를
    // 찾으려고 하기 때문에 undefined가 나옴.
    setTimeout(() => {
      console.log(this.name)
    }, 2000)
  }
}
timer.timeout()
  • 일반함수 : 현재 함수 내에서 정의된 this를 찾으려고 함.
  • 화살표함수 : 함수내에서 함수범위의 this를 찾으려고 함.

 

🧀  3. ES6 classes

 

const heropy = {
  name: 'Heropy',
  // 일반함수 ': function' 생략 가능.
  normal() {
    console.log(this.name)
  },
  arrow: () => {
    console.log(this.name)
  }
}

heropy.normal()
heropy.arrow()
// ES6 Classes

// 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 heropy = new User('Heropy', 'Park')
const amy = new User('Amy', 'Clarke')
const neo = new User('Neo', 'Smith')

console.log(heropy)
console.log(amy.getFullName())
console.log(neo.getFullName())

 

🧀  4. 상속(확장)

 

// 상속(확장)
// 1.
class Vehicle {
  constructor(name, wheel) {
    this.name = name
    this.wheel = wheel
  }
}
const myVehicle = new Vehicle('운송수단', 2)
console.log(myVehicle)


// 2.
// extends : 확장(상속)
class Bicycle extends Vehicle {
  constructor(name, wheel) {
    // Vehicle 부모요소를 그대로 가져와서 사용
    super(name, wheel)
  }
}
const myBicycle = new Bicycle('삼천리', 2)
const daughtersBicycle = new Bicycle('세발자전거', 3)
console.log(myBicycle)
console.log(daughtersBicycle)


// 3. 
class Car extends Vehicle {
  constructor(name, wheel, license) {
    // 기본적인 내용을 가져오고
    super(name, wheel)
    // 추가적인 내용 작성.
    this.license = license
  }
}
const myCar = new Car('벤츠', 4, true)
const daughtersCar = new Car('포르쉐', 4, false)
console.log(myCar)
console.log(daughtersCar)

 

 

 

 

 

 

728x90
728x90