본문 바로가기
JAVASCRIPT

[JAVASCRIPT] JAVASCRIPT 생성자, this, 클래스, 상속

by mikrw 2023. 1. 22.

객체 리터럴

const neo = {
  firstName : 'Neo',
  lastName : 'Smith'
};

 

생성자

함수명 첫글자 대문자

new 함수명

재사용 가능

 

prototype

js 객체 기본 속성

function User(first, last) {
  this.firstName = first
  this.lastName = last
}

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

const neo = new User('Neo', 'Smith')

this

자기 참조 변수

일반 함수는 호출 위치에서 따라 this 정의

화살표 함수는 자신이 선언된 함수 범위에서 this 정의

const amy = {
  name: 'Amy',
  normal: function(){
    console.log(this.name)
  },
  arrow: () => {
    console.log(this.name)
  }
}

amy.normal()  // Amy
amy.arrow()   // undefined

ES6 Classes

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

const neo = new User('Neo', 'Smith')

상속

extends

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

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

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

const myCar = new Car('벤츠', 4, true)
console.log(myCar)