생성자 함수(prototype)
function User(first, last) {
// this = {}
this.firstName = first
this.lastName = last
// return this
}
User.prototype.getFullName = function () {
return `${this.firstName} ${this.lastName}`
}
const lee = new User('lee', 'jj')
const amy = new User('Amy', 'Clarke')
- 생성자 함수 : 함수 앞에 new 키워드를 붙이면 그 함수는 생성자 함수가 된다.
- 생성자 함수의 메소드는 메모리의 효율을 위해 함수 밖에서 prototype 속성을 통해 따로 할당한다.
this
function User(name) {
this.name = name
}
// 메소드 1
User.prototype.normal = function() {
console.log(this.name)
}
// 메소드 2(화살표 함수)
User.prototype.arrow = () => {
console.log(this.name)
}
const lee = new User('lee')
lee.normal() // lee
lee.arrow() // undefined
- 일반 함수 내부에 this가 포함되어 있다면 그 this는 함수의 호출 위치에 따라서 동적으로 정의된다.
- 화살표 함수 내부에 this가 포함되어 있다면 그 this는 화살표 함수가 선언된 함수 범위에서 정적으로 정의된다.
ES6 클래스
class User {
constructor(first, last) {
this.firstName = first
this.lastName = last
}
getFullName() {
return `${this.firstName} ${this.lastName}`
}
}
- 생성자 함수와 생성자 함수의 메소드를 하나의 클래스로 합쳐서 정의할 수 있다.
- 생성자 함수는 constructor()라는 메소드로 대체된다.
ES6 클래스 상속
class Vehicle {
constructor(name, wheel) {
this.name = name
this.wheel = wheel
}
}
class Car extends Vehicle {
constructor(name, wheel, license) {
super(name, wheel)
this.license = license
}
}
- extends 키워드를 통해 미리 만들어져 있던 클래스의 속성들을 새로운 클래스가 그대로 물려받는다.
- 상속을 받은 새로운 클래스의 내부에서 super는 상속이 된, 기존의 클래스의 생성자를 뜻한다.